How do I remove the first element from an array?
Often you want to add or remove values from the start or end of an array. To remove the first value in the array and see what it is, you can use the array_shift function in PHP:
<?php
$values = array(1,2,3,4,5,6,7,8,9,10);
$first = array_shift($values);
echo "First value was: $first";
print_r($values);
?>
Which tells us this:
First value was: 1
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
[4] => 6
[5] => 7
[6] => 8
[7] => 9
[8] => 10
Notice how the keys get re-assigned after the call to array_shift, so that '2' now has a key of zero whereas in the initial array that key referenced the number '1' which has now been removed from the array.
Comment on this Question and Answer >>>
ASK A QUESTION
More arrays PHP Questions
How do I write my own sort function?when i fetch the record in the database but they skip first record in the database
How can I sort a multi-dimensional array?
How do I reverse the order of the elements in an array?
Hi. i have a music samples website. in one table, id like a different sample to appear every time the page is refreshed. how do i acheve this? how can i alterate and retrieve these bloody mp3's? surely i can use a PHP script? thankyou
