xxxxxxxxxx
<?php
// The unset method allows you to remove a key from an array in php.
$mascots = [
'ElePHPant' => 'php',
'Geeko' => 'openSUSE',
'Gopher' => 'Go'
];
unset($mascots['Gopher']);
print_r($mascots);
// Array
// (
// [ElePHPant] => php
// [Geeko] => openSUSE
// )
xxxxxxxxxx
$array = array(
"name" => "John",
"age" => 30,
"city" => "New York",
"country" => "USA"
);
$keysToRemove = array("age", "country");
foreach ($keysToRemove as $key) {
if (array_key_exists($key, $array)) {
unset($array[$key]);
}
}
print_r($array);
xxxxxxxxxx
<?php
$array = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
$keyToRemove = 'key2';
if (array_key_exists($keyToRemove, $array)) {
unset($array[$keyToRemove]);
echo "Key '$keyToRemove' has been removed from the array.";
} else {
echo "Key '$keyToRemove' does not exist in the array.";
}
// Output: Key 'key2' has been removed from the array.
?>