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
// 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
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>
Array
(
[0] => XL
[1] => gold
)
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.
?>
xxxxxxxxxx
// Sample array
$myArray = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);
$keyToRemove = "key2"; // Specify the key to remove
if (isset($myArray[$keyToRemove])) {
unset($myArray[$keyToRemove]); // Remove the specified key from the array
}
print_r($myArray); // Output the modified array
xxxxxxxxxx
<?php
$myArray = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3');
$keyToRemove = 'key2'; // The key of the element to be removed
if (array_key_exists($keyToRemove, $myArray)) {
unset($myArray[$keyToRemove]);
echo "Element with key $keyToRemove has been removed.";
} else {
echo "Element with key $keyToRemove does not exist in the array.";
}
// Print the modified array
print_r($myArray);
?>