Backend Development 4 min read

Using PHP array_shift() to Remove the First Element from an Array

This article explains the PHP array_shift() function, shows its syntax, demonstrates how it removes and returns the first element of both indexed and associative arrays, and highlights that the original array is re‑indexed after the operation.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP array_shift() to Remove the First Element from an Array

PHP is a widely used scripting language especially suited for web development, and it provides many powerful array functions, one of which is array_shift() . This function removes and returns the first element of an array while updating the original array’s keys.

The syntax of array_shift() is:

<code>mixed array_shift ( array &$array )</code>

In the following example, $fruits is an indexed array. After calling array_shift($fruits) , the first fruit "apple" is stored in $firstFruit and the remaining elements are re‑indexed.

<code>$fruits = array("apple", "banana", "orange", "grape");
$firstFruit = array_shift($fruits);

echo "第一个水果是:".$firstFruit."<br>";
echo "剩余的水果有:";
print_r($fruits);
</code>

Output:

<code>第一个水果是:apple
剩余的水果有:Array ( [0] => banana [1] => orange [2] => grape )
</code>

The function also works with associative arrays. In the next example, $person is an associative array; array_shift($person) returns the value of the first key‑value pair ("John") and removes that pair from the array.

<code>$person = array("name" => "John", "age" => 25, "gender" => "male");
$firstProperty = array_shift($person);

echo "第一个属性是:".$firstProperty."<br>";
echo "剩余的属性有:";
print_r($person);
</code>

Output:

<code>第一个属性是:John
剩余的属性有:Array ( [age] => 25 [gender] => male )
</code>

In both cases, array_shift() not only returns the first element’s value but also updates the original array, causing its indexes to be re‑ordered starting from zero.

Overall, array_shift() is a very useful PHP array function for efficiently removing the first element of an array, whether it is a simple indexed array or an associative array.

phpArrayphp-functionsassociative arrayarray_shift
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.