Best way to disable multiple array elements

The fact is that I have an array with 17 elements. I want to get the necessary elements for a certain time and remove them from the array.

Here is 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 bash needed. How do I look better?

+46
php
Oct. 25 '11 at 5:19
source share
4 answers

It looks like the extract() function will be the best tool for what you are trying to do (assuming it extracts all the keys / values ​​from the array and assign them to variables with the same names as the keys in the local area). After you extracted the contents, you could disable the entire $post , assuming that it does not contain anything that you wanted.

However, to answer your question, you can create an array of keys that you want to delete and execute a loop by explicitly disabling them ...

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

... or you can point the variable to a new array that deleted the keys ...

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

... or pass all array elements to unset() ...

 unset($arr['name'], $arr['email']); 
+64
Oct 25 '11 at 5:20
source share

Use array_diff_key to delete

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

You can use array_intersect_key if you want to provide an array of keys for storage.

+33
Nov 19 '15 at 10:13
source share

There is another way that is better than the examples above. Source: http://php.net/manual/en/function.unset.php

Instead of looping the entire array and disconnecting all of its keys, you can simply disconnect it once:

Array example:

 $array = array("key1", "key2", "key3"); 

For the whole array:

 unset($array); 

For unique keys:

 unset($array["key1"]); 

For multiple keys in one array:

 unset($array["key1"], $array["key2"], $array["key3"] ....) and so on. 

Hope this helps you in your development.

+31
Aug 01 '14 at 8:25
source share

I understand that this question is old, but I think that the best way could be this:

 $vars = array('name', 'email', 'address', 'phone'); /* needed variables */ foreach ($vars as $var) { ${$var} = $_POST[$var]; /* create variable on-the-fly */ unset($_POST[$var]); /* unset variable after use */ } 

Now you can use $ name, $ email, ... from anywhere;)

NB: extract () is not safe, so it’s not at all a question!

+2
Dec 02 '13 at 11:17
source share



All Articles