How can I remove a key and its value from an associative array?
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
(
)
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']