You can use the PHP array_shift() function remove the first element from an array in PHP. The array_shift() function returns the first value of the array. If array is empty or is not an array then NULL will be returned.
PHP array_shift() Function Syntax
1 2 3 |
array_shift(array) |
First let’s see the $stack array output :
1 2 3 4 5 6 |
<?php $stack = array("yellow", "red", "green", "orange", "purple"); print_r($stack); ?> |
Output:
1 2 3 4 5 6 7 8 9 10 |
Array ( [0] => yellow [1] => red [2] => green [3] => orange [4] => purple ) |
$stack array have 5 elements and we want to remove the first element has value “yellow”.
Remove the First element from an array
Now we will use PHP array_shift() function to remove first element of an array like in below example
1 2 3 4 5 6 7 8 9 |
<?php $stack = array("yellow", "red", "green", "orange", "purple"); // delete the first element of an array $removed = array_shift($stack); print_r($stack); ?> |
Output:
1 2 3 4 5 6 7 8 9 |
Array ( [0] => red [1] => green [2] => orange [3] => purple ) |
and “yellow” will be assigned to $removed.
1 2 3 4 5 |
<?php echo $removed; ?> |
Output:
1 2 3 |
yellow |