Current Location: Home> Latest Articles> PHP Array Function Introduction: array_shift() Usage and Example Analysis

PHP Array Function Introduction: array_shift() Usage and Example Analysis

M66 2025-06-20

PHP Array Function Introduction: array_shift() Usage and Example Analysis

PHP is a widely used scripting language, particularly suited for web development. PHP offers many powerful array functions, and one of the most practical is array_shift()

Here, $array is the array to be operated on, passed by reference.

Example: Basic Usage of array_shift() Function

Let’s look at an example to see how array_shift() works:

$fruits = array("apple", "banana", "orange", "grape");
$firstFruit = array_shift($fruits);
echo "The first fruit is: " . $firstFruit . "<br>";
echo "The remaining fruits are: ";
print_r($fruits);

The output will be:

The first fruit is: apple
The remaining fruits are: Array ( [0] => banana [1] => orange [2] => grape )

In this example, the array_shift() function removes the first element ("apple") from the array $fruits and stores it in the $firstFruit variable. The $fruits array is then updated, leaving only "banana", "orange", and "grape".

array_shift() Updates Array Keys

It’s important to note that array_shift() not only returns the removed element but also updates the array's keys. In this case, the original array’s indices are reordered, starting from [0].

Working with Associative Arrays

array_shift() can also be used with associative arrays. Here’s an example:

$person = array("name" => "John", "age" => 25, "gender" => "male");
$firstProperty = array_shift($person);
echo "The first property is: " . $firstProperty . "<br>";
echo "The remaining properties are: ";
print_r($person);

The output will be:

The first property is: John
The remaining properties are: Array ( [age] => 25 [gender] => male )

As you can see, the array_shift() function works the same way with associative arrays as it does with regular arrays. It removes and returns the first key-value pair’s value, while updating the array's keys.

Summary

In summary, array_shift() is a very useful PHP array function. It allows you to easily remove and return the first element from an array while updating the array's keys. Whether dealing with regular arrays or associative arrays, array_shift() works effectively and efficiently. Developers can use this function flexibly in their code to make it simpler and more efficient.