114

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?

alex
  • 479,566
  • 201
  • 878
  • 984
Turtel
  • 1,221
  • 2
  • 9
  • 8
  • This is almost certainly an [XY Problem](https://meta.stackexchange.com/q/66377/352329). There probably isn't any beneficial reason to unset these elements. And if you have concerns regarding variable scope, there may be better ways to address them than explicitly unsetting, but we cannot advise without more/better context. – mickmackusa May 10 '22 at 07:13

6 Answers6

170

Use array_diff_key to remove

$remove = ['telephone', 'country'];

$remaining = array_diff_key($post, array_flip($remove));

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

Martijn
  • 15,791
  • 4
  • 36
  • 68
Tim
  • 4,471
  • 5
  • 36
  • 42
  • smart but slow for large input arrays. foreach unset seems much faster with big input arrays and (at least) relatively small number of keys to unset. – slepic Oct 26 '19 at 07:07
  • 1
    Be careful: if the value of the field you want to remove is equal to the index of the (flipped) element you want to remove the key will not be removed. It can lead to security problems by exposing data. Can see the results here: https://replit.com/@xbeat/unset-array-of-key#index.php – Giuseppe Canale Jun 15 '22 at 15:00
109

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']);
alex
  • 479,566
  • 201
  • 878
  • 984
  • 10
    [array_diff_key()](http://php.net/manual/en/function.array-diff-key.php) is a nice solution. Thought I would add that you can use [array_intersect_key()](http://php.net/manual/en/function.array-intersect-key.php) to do the reverse, keep only certain elements – batfastad Jul 26 '14 at 00:34
  • By chance I was just doing this thing with the foreach unset. Then I thought there could be a better solution. Google lead me here. So i tried array_diff_key and it turns out that it is much much slower than foreach for large input arrays (at least when the number of keys to unset is relatively small.). – slepic Oct 26 '19 at 07:04
  • Be careful using array_flip solution: if the value of the field you want to remove is equal to the index of the (flipped) element you want to remove the key will not be removed. It can lead to security problems by exposing data. Can see the results here: replit.com/@xbeat/unset-array-of-key#index.php – Giuseppe Canale Jun 15 '22 at 15:06
64

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

Instead of looping thorough the entire array and unsetting all its keys, you can just unset it once like so:

Example Array:

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

For the entire 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.

I hope this helps you in your development.

Rob
  • 4,927
  • 12
  • 49
  • 54
CodingDaily
  • 641
  • 5
  • 2
4

I understand this question is old, but I think an optimal way might be to do 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 completely out of question!

2
<?php
   $name = $post['name'];
   $email = $post['email'];
   $address = $post['address'];
   $telephone = $post['telephone'];
   $country = $post['country'];



   
   $myArray = array_except($post, ['name', 'email','address','telephone','country']);
   
  print_r($myArray);
  
  
   
  function array_except($array, $keys){
    foreach($keys as $key){
        unset($array[$key]);
    }
    return $array;
  }
?>
ahmedkandil
  • 477
  • 3
  • 6
1

In php unset function can take multiple arguments

$test = ['test1' => 1, 'test2' => 4, 'test34' => 34];

unset($test['test1'], $test['test34']);

Here is this description from documentation

unset(mixed $var, mixed ...$vars): void
Levon Babayan
  • 266
  • 2
  • 18