In this short article, we’ll look at a couple of examples of removing array elements by their key.
Full code listing below:
$array = [
1 => 'One',
'Two' => 3,
'Three' => 'Three',
4 => NULL,
];
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";
if(isset($array['Two']))
{
unset($array['Two']);
}
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";
if(isset($array[4]))
{
unset($array[4]);
}
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";
if(array_key_exists(4, $array))
{
unset($array[4]);
}
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";Here’s what we have:
$array = [ 1 => 'One', 'Two' => 3, 'Three' => 'Three', 4 => NULL, ]; echo "<pre dir='ltr'>";print_r($array); echo "</pre>";
Initialization of an array with four values (pay attention to the last one).
Removing an array element by key is no different than deleting a regular variable. To do this, you need to use PHP’s `unset()` function, passing the variable to be deleted as the argument. But before deleting anything, it's a good practice to check whether the variable has been initialized. Otherwise, an error may occur.
To check this, you can use the following condition:
if(isset($array['Two']))
{
unset($array['Two']);
}
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";and immediately verify the result. As you can see, the array has been reduced by one record.
Let’s continue our test and try to remove the element with key `4`:
if(isset($array[4]))
{
unset($array[4]);
}
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";After checking the result, we find that the value hasn’t been deleted. The issue lies in the conditional operator and the `isset()` function. The thing is, `isset()` doesn’t return true for a variable that has a `NULL` value. That’s why in such cases, it’s better to use the `array_key_exists()` function:
if(array_key_exists(4, $array))
{
unset($array[4]);
}
echo "<pre dir='ltr'>";print_r($array); echo "</pre>";We check the result — yes, everything is fine, the value was removed.
