Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to unset multiple array elements

Tags:

php

The deal here is that I have an array with 17 elements. I want to get the elements I need for a certain time and remove them permanently from the array.

Here's the code:

$name = $post['name']; $email = $post['email']; $address = $post['address']; $telephone = $post['telephone']; $country = $post['country'];  unset($post['name']); unset($post['email']); unset($post['address']); unset($post['telephone']); unset($post['country']); 

Yes the code is ugly, no need to bash. How do I make this look better?

like image 428
Turtel Avatar asked Oct 25 '11 05:10

Turtel


People also ask

How do you unset multiple values in PHP?

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().

How do you unset an array array?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.

How do I reindex an array?

The re-index of an array can be done by using some inbuilt function together. These functions are: array_combine() Function: The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values.


2 Answers

Use array_diff_key to remove

$remove = ['telephone', 'country'];  array_diff_key($post, array_flip($remove)); 

You could use array_intersect_key if you wanted to supply an array of keys to keep.

like image 137
Tim Avatar answered Sep 25 '22 06:09

Tim


It looks like the function extract() would be a better tool for what you're trying to do (assuming it's extract all key/values from an array and assign them to variables with the same names as the keys in the local scope). After you've extracted the contents, you could then unset the entire $post, assuming it didn't contain anything else you wanted.

However, to actually answer your question, you could create an array of the keys you want to remove and loop through, explicitly unsetting them...

$removeKeys = array('name', 'email');  foreach($removeKeys as $key) {    unset($arr[$key]); } 

...or you could point the variable to a new array that has the keys removed...

$arr = array_diff_key($arr, array_flip($removeKeys)); 

...or pass all of the array members to unset()...

unset($arr['name'],  $arr['email']); 
like image 32
alex Avatar answered Sep 21 '22 06:09

alex