gsquare567 gsquare567 - 5 months ago 12
PHP Question

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

Given an associative array:

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


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

Answer

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
(
)