Removing Keys from an Array in PHP

Removing one or more keys from an array in PHP seems like something that should be easy to do. Yet out of the 70+ array functions in PHP, there is no single function to do it. But here’s the easy way:

Use array_diff_key()

PHP has a function called array_diff_key($array1, $array2) that returns an array with all of the keys (and their values) from $array1 that don’t also occur in $array2. We can use this to quickly cobble together a solution:

<?php
 
function array_remove_keys($array, $keys) {
 
    // array_diff_key() expected an associative array.
    $assocKeys = array();
    foreach($keys as $key) {
        $assocKeys[$key] = true;
    }
 
    return array_diff_key($array, $assocKeys);
}
 
// Example:
$data = array(
    'name' => 'Brian',
    'address1' => '98 Market St.',
    'address2' => 'N/A'
);
 
// Output before array_remove_keys()
var_dump($data);
 
// Remove address2 key.
$data = array_remove_keys($data, array('address2'));
 
// Output after array_remove_keys()
var_dump($data);
 
/* Output:
 
array(3) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
  ["address2"]=>
  string(3) "N/A"
}
array(2) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
}
*/

Works great! But it’s not quite complete. There is absolutely no error checking, and passing an array as the second parameter isn’t the most convenient way to operate. Let’s give the caller the option of passing either an array, or a comma-separated list of keys to delete.

<?php
 
function array_remove_keys($array, $keys = array()) {
 
	// If array is empty or not an array at all, don't bother
	// doing anything else.
	if(empty($array) || (! is_array($array))) {
		return $array;
	}
 
	// If $keys is a comma-separated list, convert to an array.
	if(is_string($keys)) {
		$keys = explode(',', $keys);
	}
 
	// At this point if $keys is not an array, we can't do anything with it.
	if(! is_array($keys)) {
		return $array;
	}
 
    // array_diff_key() expected an associative array.
    $assocKeys = array();
    foreach($keys as $key) {
        $assocKeys[$key] = true;
    }
 
    return array_diff_key($array, $assocKeys);
}
 
// Example:
$data = array(
    'name' => 'Brian',
    'address1' => '98 Market St.',
    'address2' => 'N/A'
);
 
// Output before array_remove_keys()
var_dump($data);
 
// Remove address2 key.
$data = array_remove_keys($data, 'address2');
 
// Output after array_remove_keys()
var_dump($data);
 
/* Output:
 
array(3) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
  ["address2"]=>
  string(3) "N/A"
}
array(2) {
  ["name"]=>
  string(5) "Brian"
  ["address1"]=>
  string(13) "98 Market St."
}
*/