PHP: Removing an element from an array.

This is a short guide on how to remove an element from a PHP array.

Removing elements from a PHP array is actually pretty simple. By far the most popular approach is to use the function unset, which destroys a given variable:

<?php

//Example array.
$myArray = array('Cat', 'Dog', 'Horse');

//var_dump it out, for example purposes.
var_dump($myArray);

//Delete Cat, which has the index "0".
unset($myArray[0]);

//var_dump it out again.
var_dump($myArray);

?>

As you probably already know, array elements have indexes. These indexes start at 0. i.e. The first element in an array will have the index 0, whereas the second element will have the index 1 (and so on).

In the code above, you can see that we “unset” the element with the index 0. If we wanted to remove the “Dog” element, then we’d have to unset index 1.

In certain cases, you might have custom indexes (associative arrays). Fortunately, the approach is much the same. To remove an element from an associative array, you simply need to supply your custom index to the unset function:

<?php

//Example array.
$myArray = array(
    'city' => 'Paris',
    'country' => 'France',
    'continent' => 'Europe'
);

//var_dump it out so that we can see its structure.
var_dump($myArray);

//Remove the "Paris" element, which has the index "city".
unset($myArray['city']);

//var_dump it out again so that we can see the result.
var_dump($myArray);

?>

OK, but what if we want to remove an element without knowing what its index is? Well, in this case, we need to search for it and find its index before attempting to delete it.

<?php

/**
 * Remove an element from an array.
 * 
 * @param string|int $element
 * @param array $array
 */
function deleteElement($element, &$array){
    $index = array_search($element, $array);
    if($index !== false){
        unset($array[$index]);
    }
}

//Example array containing city names.
$cities = array('London', 'Dublin', 'Boston');

//Print it out.
var_dump($cities);

//Use our custom function to delete the element "London".
deleteElement('London', $cities);

//View the result.
var_dump($cities);

As you can see, I’ve create a custom function. This function searches the given array for a specific element. If the element index is found, we delete it. If not, it doesn’t do anything.

Be sure to mess around with some of the examples I’ve provided!