PHP function to remove array element based on array key

Here is a small and simple PHP function to remove one or more than one array elements based on the keys of the array. You need to pass the original array along with the keys. Keys may be only one as a string or it may the array of keys. Resulting array would be the filtered array and preserved with array keys. If the given key is not found original array will be returned.

Here is the PHP code.

/**
* Remove array element based on array key
* @param $arr - The Input Array
* @param $key ; String or Array ; keys which will need be removed from Array
* @return array ; Returns the resulting array
*/
function array_filter_by_keys($arr, $keys) 
{
if(!is_array($keys))
$keys = array($keys);
$array_keys = array_keys($arr);
foreach($arr as $array_key => $value) {
if(in_array($array_key,$keys))
unset($arr[$array_key]);
}
return $arr;
}

Example 1

$myarray = array(
'nepal' => 'Kathmandu',
'india' => 'New Delhi',
'japan' => 'Tokyo',
'bhutan' => 'Thimpu'
);

$new_array = array_filter_by_keys($myarray,array('bhutan','india'));

Output :

Array ( [nepal] => Kathmandu [japan] => Tokyo )

Example 2

$myarray = array(
'nepal' => 'Kathmandu',
'india' => 'New Delhi',
'japan' => 'Tokyo',
'bhutan' => 'Thimpu'
);

$new_array = array_filter_by_keys($myarray,'japan');

Output :

Array ( [nepal] => Kathmandu [india] => New Delhi [bhutan] => Thimpu )

Leave a Reply

Your email address will not be published. Required fields are marked *