Understanding PHP's array_shift() Function: Syntax, Parameters, Return Values, and Practical Examples
This article explains PHP's array_shift() function, covering its syntax, parameters, return value, and demonstrating its use with examples for basic arrays, empty arrays, and associative arrays; it also shows how the function modifies the original array and what it returns when the array is empty.
PHP is a popular scripting language widely used for web development, offering many built‑in functions for array manipulation, including the useful array_shift() function.
The array_shift() function removes the first element from an array, returns its value, reduces the array length by one, and reindexes the remaining elements, making it ideal for queue or list handling.
Syntax:
<code>array_shift(array $array): mixed</code>Parameter:
$array – the array to operate on.
Return value:
mixed – the value of the removed first element, or NULL if the array is empty.
Example 1 – Basic usage:
<code>$fruits = array("apple", "banana", "orange");
$firstFruit = array_shift($fruits);
echo "First fruit: " . $firstFruit; // Output: First fruit: apple
print_r($fruits); // Output: Array ( [0] => banana [1] => orange )
</code>This example demonstrates removing "apple" from $fruits , leaving "banana" and "orange" with updated indexes.
Example 2 – Handling an empty array:
<code>$emptyArray = array();
$firstElement = array_shift($emptyArray);
echo "First element: " . $firstElement; // Output: First element:
print_r($emptyArray); // Output: Array ( )
</code>When the array is empty, array_shift() returns NULL and the array remains unchanged.
Example 3 – Working with an associative array:
<code>$student = array(
"name" => "John",
"age" => 20,
"gender" => "male"
);
$firstAttribute = array_shift($student);
echo "First attribute: " . $firstAttribute; // Output: First attribute: John
print_r($student); // Output: Array ( [age] => 20 [gender] => male )
</code>For associative arrays, the function returns the value of the first key ("John") and removes that entry, leaving the remaining key‑value pairs.
Summary: The array_shift() function is a versatile tool for PHP developers to efficiently remove and retrieve the first element of both indexed and associative arrays, useful in queue processing and other array‑handling scenarios.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.