Php unset all values

How to Recursively Unset Array Keys and Object Properties in PHP

PHP’s unset() function doesn’t go deep. Here’s the 5 short functions you need to efficiently prune multi-dimensional datasets in PHP.

Recently, I implemented a frontend UX that asynchronously loads data from an API. The server-side requests to the API return nested records, each with their own resource IDs. Since the frontend didn’t need these IDs, I wanted to strip them before passing the dataset back to the frontend. That’s why I wrote some functions to recursively unset fields in my multi-dimensional datasets!

Now, there are two different ways to represent maps (key-value pairs) in PHP: objects and arrays.

Sometimes SDKs will parse data into objects while other SDKs will return data as associative arrays. To cover all cases, I’ve written the four different functions (plus a bonus, fifth function) that you need to recursively unset data fields.

Notice that an ampersand (&) precedes the first parameter in each of the following functions. This is how to pass variables by reference in PHP. By passing a variable by reference, the function makes direct modifications to that variable’s value rather than returning a modified copy. This makes the functions much more efficient!

Читайте также:  Arraylist java class code

Note that PHP’s unset() function doesn’t throw an error or warning when given non-existent fields. This means the following functions may be safely called without preliminary deep checks.

Deep Unset Object Properties

Use this function when you want to only unset a specific property in every object instance. Array keys by the same name will remain.

/** * Unsets object properties of the given name. * * @param array|object $data An iterable object or array to modify. * @param string $prop The name of the property to remove. */ function deep_unset_prop( array|object &$data, string $prop ) < if ( is_object( $data ) ) < unset( $data-> ); > foreach ( $data as &$value ) < if ( is_array( $value ) || is_object( $value ) ) < deep_unset_prop( $value, $prop ); >> >

Example Usage

$employees = json_decode( $employees_json, false );// Employees as objects. deep_unset_prop( $employees, 'id' );// Remove all "id" properties. print_r( $employees );// See the result.

Deep Unset Array Keys

Use this function when you want to only unset a specific key in every associative array. Object properties by the same name will remain.

/** * Unsets array keys of the given name. * * @param array|object $data An iterable object or array to modify. * @param string $key The name of the array key to remove. */ function deep_unset_key( array|object &$data, string $key ) < if ( is_array( $data ) ) < unset( $data[ $key ] ); >foreach ( $data as &$value ) < if ( is_array( $value ) || is_object( $value ) ) < deep_unset_key( $value, $key ); >> >

Example Usage

$employees = json_decode( $employees_json, true );// Employees as arrays. deep_unset_key( $employees, 'id' );// Remove all "id" keys. print_r( $employees );// See the result.

Deep Unset Object Properties & Array Keys

Ideally your dataset does not mingle associative arrays and objects. Otherwise, you’ll find yourself repeatedly wondering, “Ugh! Do I use -> or [] to access the fields this time?!”

For a one-size-fits-all solution, the following function is all you need!

/** * Unsets array keys and object properties of the given name. * * @param array|object $data An iterable object or array to modify. * @param string $field The name of the key or property to remove. */ function deep_unset( array|object &$data, string $field ) < if ( is_array( $data ) ) < unset( $data[ $field ] ); >elseif ( is_object( $data ) ) < unset( $data-> ); > foreach ( $data as &$value ) < if ( is_array( $value ) || is_object( $value ) ) < deep_unset( $value, $field ); >> >

Example Usage

deep_unset( $employees, 'id' );// Remove all "id" properties and keys. print_r( $employees );// See the result.

Deep Unset Multiple Fields

Additionally, you may want to recursively unset multiple fields at once. This function lets you specify a variable number of fields to remove altogether!

/** * Unsets all array keys and object properties of the given names. * * @param array|object $data An iterable object or array to modify. * @param string[] $fields The names of the keys or properties to remove. */ function deep_unset_all( array|object &$data, . $fields ) < if ( is_array( $data ) ) < foreach ( $fields as &$f ) < unset( $data[ $f ] ); >> elseif ( is_object( $data ) ) < foreach ( $fields as &$f ) < unset( $data-> ); > > foreach ( $data as &$value ) < if ( is_array( $value ) || is_object( $value ) ) < deep_unset_all( $value, . $fields ); >> >

Example Usage

The unwanted fields may be specified sequentially like this:

deep_unset_all( $employees, 'id', 'title', 'does_not_exist' ); print_r( $employees );// See the result.

To pass an array of unwanted fields, use the spread operator to first unpack the names like this:

$fields_to_remove = [ 'id, 'title', 'does_not_exist' ]; deep_unset_all( $employees, . $fields_to_remove ); print_r( $employees );// See the result.

Deep Unset All Foreign Fields

Okay, now sometimes you know what fields you do want and just need to throw out the rest. Here’s how to recursively unset every field except the ones you need to keep.

With this function, you can specify the exact fields you need rather than guess all the possible fields that you don’t need!

/** * Unsets all array keys and object properties that are not * of the given names. * * @param array|object $data An iterable object or array to modify. * @param string[] $fields The names of the keys or properties to keep. */ function deep_unset_except( array|object &$data, . $fields ) < if ( is_array( $data ) ) < foreach ( $data as $key =>&$_ ) < if ( is_string( $key ) && ! in_array( $key, $fields, true ) ) < unset( $data[ $key ] ); >> > elseif ( is_object( $data ) ) < foreach ( $data as $prop =>&$_ ) < if ( ! in_array( $prop, $fields, true ) ) < unset( $data-> ); > > > foreach ( $data as &$value ) < if ( is_array( $value ) || is_object( $value ) ) < deep_unset_except( $value, . $fields ); >> >

Example Usage

Same as the previous function, the fields may be specified sequentially or unpacked from an array:

$fields_to_keep = [ 'name', 'title', 'subordinates' ]; deep_unset_except( $employees, . $fields_to_keep ); print_r( $employees );// See the result.

Full-stack web developer, specialized in WordPress and API integrations. Currently focused on building Completionist, the Asana integration WordPress plugin.

Источник

unset

unset() удаляет перечисленные переменные.

Поведение unset() внутри пользовательской функции может отличаться, в зависимости от того, какой тип имеет переменная, которую необходимо удалить.

Если переменная, объявленная глобальной, удаляется внутри функции, то будет удалена только локальная переменная. Переменная в области видимости вызова функции сохранит то же значение, что и до вызова unset() .

$foo = ‘bar’ ;
destroy_foo ();
echo $foo ;
?>

Результат выполнения данного примера:

Если необходимо удалить глобальную переменную внутри функции, то для этого нужно использовать массив $GLOBALS :

Если переменная, которая передается ПО ССЫЛКЕ, удаляется внутри функции, то будет удалена только локальная переменная. Переменная в области видимости вызова функции сохранит то же значение, что и до вызова unset() .

$bar = ‘something’ ;
echo » $bar \n» ;

Результат выполнения данного примера:

Если статическая переменная удаляется внутри функции, unset() удалит переменную только в контексте дальнейшего выполнения функции. При последующем вызове предыдущее значение переменной будет восстановлено.

function foo ()
static $bar ;
$bar ++;
echo «До удаления: $bar , » ;
unset( $bar );
$bar = 23 ;
echo «После удаления: $bar \n» ;
>

Результат выполнения данного примера:

До удаления: 1, После удаления: 23 До удаления: 2, После удаления: 23 До удаления: 3, После удаления: 23

Источник

unset

unset() удаляет перечисленные переменные.

Поведение unset() внутри пользовательской функции может отличаться, в зависимости от того, какой тип имеет переменная, которую необходимо удалить.

Если переменная, объявленная глобальной, удаляется внутри функции, то будет удалена только локальная переменная. Переменная в области видимости вызова функции сохранит то же значение, что и до вызова unset() .

$foo = ‘bar’ ;
destroy_foo ();
echo $foo ;
?>

Результат выполнения данного примера:

Если необходимо удалить глобальную переменную внутри функции, то для этого нужно использовать массив $GLOBALS :

Если переменная, которая передается ПО ССЫЛКЕ, удаляется внутри функции, то будет удалена только локальная переменная. Переменная в области видимости вызова функции сохранит то же значение, что и до вызова unset() .

$bar = ‘something’ ;
echo » $bar \n» ;

Результат выполнения данного примера:

Если статическая переменная удаляется внутри функции, unset() удалит переменную только в контексте дальнейшего выполнения функции. При последующем вызове предыдущее значение переменной будет восстановлено.

function foo ()
static $bar ;
$bar ++;
echo «До удаления: $bar , » ;
unset( $bar );
$bar = 23 ;
echo «После удаления: $bar \n» ;
>

Результат выполнения данного примера:

До удаления: 1, После удаления: 23 До удаления: 2, После удаления: 23 До удаления: 3, После удаления: 23

Источник

PHP deleting elements of an array by unset ( key or value )

Array Delete

We can remove an element from an array by using unset command.
This unset command takes the array key as input and remove that element from the array. After removal the associated keys and values ( of other balance elements ) does not change.

Array Unset

Here we are removing the element with key=3. If the array has 7 elements and if try to delete 9th element then unset command will not return any error but nothing will be deleted.

Here is an example how unset command is used.

How to delete an element by using value ( not key ) from an array

In the above examples we have used key if the array as input to remove the element from the array. If we don’t know the key and we know the value then how to remove the element?

There is no direct function to do this but we can use array_diff function to remove the element by using the value. Note that array_diff function takes two arrays as input. Here is the code , we want to remove d from our $input array.

$new_array=array_diff($input,array("d"));
$remove=array(c,f); $new_array=array_diff($input,$remove);
while (list ($key, $val) = each ($new_array)) < echo "$key ->$val 
";>
$input=array(a,b,c,d,e,f,g); unset($input[array_search('d',$input)]); while (list ($key, $val) = each ($input)) < echo "$key ->$val 
"; >
0 -> a 1 -> b 2 -> c 4 -> e 5 -> f 6 -> g

  • Array Adding & Removing Elements
  • array_pop(): Removing Last element of the Array
  • array_shift(): Removing First element of the Array
  • array_unset(): Removing element from any position of the Array
  • array_push(): Adding elements at the end of the Array
  • array_unshift(): Adding elements at the beginning of the Array

Questions

  1. How do you delete a specific key-value element from an array using the `unset` command in PHP?
  2. What is the syntax for using the `unset` command to remove an element from an array?
  3. Can you delete multiple key-value elements from an array using a single `unset` command in PHP?
  4. How do you handle cases where the specified key does not exist in the array while using `unset`?
  5. Can you use the `unset` command to delete nested or multidimensional array elements in PHP?
  6. What are the effects of using `unset` on an array? Does it reindex the remaining elements?
  7. How do you check if an element has been successfully deleted from an array after using `unset`?
  8. Are there any alternative methods or functions in PHP to delete elements from an array, other than `unset`?
  9. What precautions should be taken when using `unset` to delete elements from an array to avoid unexpected behavior?
  10. Can you use the `unset` command to remove an element by its value rather than its key in PHP?

plus2net.com

Click here for More on PHP Array functions

  • Array functions in PHP
  • array : Creating an Array
  • Multidimensional array : Creating and displaying
  • array_diff Difference of two arrays
  • array_count_values counting the frequency of values inside an array
  • count : sizeof Array Size or length
  • array_push : Adding element to an Array
  • array_merge : Adding two arrays
  • array_sum : Array Sum of all elements
  • array_keys : To get array of keys from an array
  • max Getting the maximum or Minimum value of elements in an array
  • current Value of present cursor element in an array
  • reset Moves the internal pointer to first element
  • end Moves the internal pointer to last element
  • Array checkbox
  • array_map : Using user defined and native function to each element of an array
  • current : Returns current element
  • reset : Move cursor to first element
  • end : Move cursor to last element
  • next : Move cursor to next
  • prev : Move cursor to previous element
  • in_array : IN Array to search for elements inside an array
  • is_array : To check the variable is array or not
  • array_rand : Random elements of Array
  • array_unique : Array Unique values
  • Breaking of strings to create array using split command
  • Session Array to maintain data in different pages
  • unset : Deleting elements of an array by using its key or value
  • sort: sorting of PHP array
  • usort: Sorting array by using user defined function
  • Displaying the elements of an array
  • Filtering elements and returning new array based on callback function
  • Applying user function to each element of an array
  • http_build_query: generate query string using elements to pass through URL

Источник

Оцените статью