PHP Manipulating an Array Removing elements from an array

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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
)


Got any PHP Question?