Php unset all keys

How to Remove Multiple Keys from PHP Array?

In this example, we will remove array elements by keys array in php. we can delete multiple keys from array php. basically we will unset multiple keys from php array.

if you see in php documentation there are not available directly remove multiple keys from php array. But we will create our own php custom function and remove all keys by given array value.

In this example i created custom function as array_except(). you need to pass one main array and another will be keys array that you want to remove it.

So let’s see bellow example:

$myArray = [

‘name’=>’Hardik Savani’,

’email’=>’savanihd@gmail.com’,

‘gender’=>’male’,

‘website’=>’itsolutionstuff.com’

];

$newArray = array_except($myArray, [‘gender’, ’email’]);

print_r($newArray);

function array_except($array, $keys) foreach($keys as $key) unset($array[$key]);

>

return $array;

>

?>

Array

(

[name] => Hardik Savani [website] => itsolutionstuff.com

)

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

We are Recommending you

  • PHP MySQL Create Dynamic Treeview Example
  • PHP MySQL Column Sorting Example Tutorial
  • PHP MySQL Login with Google Account Example
  • PHP MySQL DataTables Server-side Processing Example
  • How to Get File Name without Extension in PHP?
  • How to Remove White Space from String in PHP?
  • How to Remove Specific Element by Value from Array in PHP?
  • How to Remove undefined Value from Array in JQuery?
  • How to Get Maximum Key Value of Array in PHP?
  • How to Remove Empty Values from Array in PHP?
  • How to Add Prefix in Each Key of PHP Array?
  • How to Get Minimum Key Value of Array in PHP?
  • How to Remove Null Values from Array in PHP?
  • How can Make an Array from the Values of Another Array’s Key Value?

Источник

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!

Читайте также:  Валидный номер python решение

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!

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.

Читайте также:  Html java всплывающее окно

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.

Источник

Remove key and value from an associative array in PHP

To remove a key and its respective value from an associative array in PHP you can use the unset() function.

<?php $mascots = [ 'ElePHPant' => 'php', 'Geeko' => 'openSUSE', 'Gopher' => 'Go' ]; unset($mascots['Gopher']); print_r($mascots); // Array // ( // [ElePHPant] => php // [Geeko] => openSUSE // ) 

As the name of the function suggests, you use the unset() function to unset a given variable or in this case an array key with its value.

Читайте также:  Метод arrays fill java

Remove multiple keys from associative array

Removing multiple keys from associative array can be done using the unset() as well. You can pass as many keys to unset as arguments to the unset() function. See the example below where two keys are dropped from the associative array.

<?php $mascots = [ 'ElePHPant' => 'php', 'Geeko' => 'openSUSE', 'Gopher' => 'Go' ]; unset($mascots['Gopher'], $mascots['Geeko']); print_r($mascots); // Array // ( // [ElePHPant] => php // ) 

However useful, the approach above might get somewhat tedious when you need to remove multiple keys from the associative array. In that case there is another option, the array_diff() function. The array_diff() function compares the array you pass it as its first argument and returns an array with the values not present in the array you pass it in the second array.

In contrast to the other options I present here this approach require you to specify the values for which you remove the keys (and values). Instead of keys for which you wish to remove the values (and keys).

<?php $mascots = [ 'ElePHPant' => 'php', 'Geeko' => 'openSUSE', 'Gopher' => 'Go' ]; $values = array_diff($mascots, ['openSUSE', 'Go']); print_r($values); // Array // ( // [ElePHPant] => php // ) 

This last approach seems especially convenient if you need to remove the keys (and values) dynamically in your code.

Remove all keys from associative array

To remove all keys from an associative PHP array is to basically turn the array into a regular numerically indexed array. This can be achieved by grabbing just the values from the associative PHP array.

Since associative arrays in PHP are ordered, just like numerically indexed arrays, we can grab just the values and maintain the original order of the array.

<?php $mascots = [ 'ElePHPant' => 'php', 'Geeko' => 'openSUSE', 'Gopher' => 'Go' ]; $values = array_values($mascots); print_r($values); // Array // ( // [0] => php // [1] => openSUSE // [2] => Go // ) 

Источник

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