How can I remove a key and its value from an associative array?

04/02/2020 17:00:01

Given an associative array:

array("key1" => "value1", "key2" => "value2", ...)

How would I go about removing a certain key-value pair, given the key?

Verified Answer (368 Votes)

06/16/2010 18:15:15

You can use unset:

unset($array['key-here']);

Example:

$array = array("key1" => "value1", "key2" => "value2");
print_r($array);

unset($array['key1']);
print_r($array);

unset($array['key2']);
print_r($array);

Output:

Array
(
    [key1] => value1
    [key2] => value2
)
Array
(
    [key2] => value2
)
Array
(
)
368

Answer #2 (27 Votes)

06/16/2010 18:15:33

Use unset():

unset($array['key1']);
27

Answer #3 (20 Votes)

09/01/2015 15:56:08

Use this function to remove specific arrays of keys without modifying the original array:

function array_except($array, $keys) {
  return array_diff_key($array, array_flip((array) $keys));   
} 

First param pass all array, second param set array of keys to remove.

For example:

$array = [
    'color' => 'red', 
    'age' => '130', 
    'fixed' => true
];
$output = array_except($array, ['color', 'fixed']);
// $output now contains ['age' => '130']
20
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.