PHP Removing elements from an array


Example

To remove an element inside an array, e.g. the element with the index 1.

$fruit = array("bananas", "apples", "peaches");
unset($fruit[1]);

This will remove the apples from the list, but notice that unset does not change the indexes of the remaining elements. So $fruit now contains the indexes 0 and 2.

For associative array you can remove like this:

$fruit = array('banana', 'one'=>'apple', 'peaches');

print_r($fruit);
/*
    Array
    (
        [0] => banana
        [one] => apple
        [1] => peaches
    )
*/

unset($fruit['one']); 

Now $fruit is

print_r($fruit);

/*
Array
(
    [0] => banana
    [1] => peaches
)
*/

Note that

unset($fruit);

unsets the variable and thus removes the whole array, meaning none of its elements are accessible anymore.

Removing terminal elements

array_shift() - Shift an element off the beginning of array.

Example:

  $fruit = array("bananas", "apples", "peaches");
  array_shift($fruit);
  print_r($fruit);

Output:

 Array
(
    [0] => apples
    [1] => peaches
)

array_pop() - Pop the element off the end of array.

Example:

  $fruit = array("bananas", "apples", "peaches");
  array_pop($fruit);
  print_r($fruit);

Output:

 Array
(
    [0] => bananas
    [1] => apples
)