Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all array elements except for a given key

Simple one, I was just wondering if there is a clean and eloquent way of returning all values from an associative array that do not match a given key(s)?

$array = array('alpha' => 'apple', 'beta' => 'banana', 'gamma' => 'guava');  $alphaAndGamma = arrayExclude($array, array('alpha')); $onlyBeta      = arrayExclude($array, array('alpha', 'gamma'));  function arrayExclude($array, Array $excludeKeys){     foreach($array as $key => $value){         if(!in_array($key, $excludeKeys)){             $return[$key] = $value;         }     }     return $return; } 

This is what I'm (going to be) using, however, are there cleaner implementations, something I missed in the manual perhaps?

like image 306
Dan Lugg Avatar asked Feb 28 '11 21:02

Dan Lugg


People also ask

How do you remove an array from a key?

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 find a key in an array?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

What is Array_flip function in PHP?

The array_flip() function flips/exchanges all keys with their associated values in an array.


1 Answers

Although, this question is too old and there are several answer are there for this question, but I am posting a solution that might be useful to someone.

You may get the all array elements from provided input except the certain keys you've defined to exclude using:

$result = array_diff_key($input, array_flip(["SomeKey1", "SomeKey2", "SomeKey3"])); 

This will exclude the elements from $input array having keys SomeKey1, SomeKey2 and SomeKey3 and return all others into $result variable.

like image 145
Dev Avatar answered Oct 04 '22 19:10

Dev