The array_shift function is used to remove the first element of the array and return the removed element value. After removal, all elements of the array will automatically move forward, and the index will be reordered (if it is an indexed array).
array_shift(array &$array): mixed
The parameter $array is the array passed in (must be a variable, not a direct array literal).
The return value is the first element that was removed. If the array is empty, return null .
Suppose there is an array:
<?php
$fruits = ['apple', 'banana', 'cherry'];
$firstFruit = array_shift($fruits);
echo "The first element removed is: " . $firstFruit . "\n"; // Output:apple
print_r($fruits); // Now the array is ['banana', 'cherry']
?>
In the above example, apple is removed and assigned to $firstFruit , and the original array $fruits is left with banana and cherry .
Confirm that the array is not empty <br> It is best to confirm that the array is not empty before calling array_shift to prevent accidental return of null , resulting in subsequent logical errors.
Pass in variables
array_shift needs to pass in variables (references) and cannot directly pass in array literals or function return values, otherwise an error will be reported.
Maintain data consistency <br> Using array_shift will modify the original array, making sure that this is the expected operation and avoid affecting other variables that reference the same array.
In order to avoid the problem caused by calling array_shift in empty arrays, you can judge it in combination with empty or count :
<?php
if (!empty($array)) {
$firstElement = array_shift($array);
// Continue to process $firstElement
} else {
// The array is empty,Process the corresponding logic
}
?>
Suppose you remove the first element from the result array returned by an API and access its data:
<?php
$response = ['status' => 'ok', 'data' => ['item1', 'item2', 'item3']];
// Remove data The first element of the array
if (!empty($response['data'])) {
$firstItem = array_shift($response['data']);
echo "The first data item: " . $firstItem;
} else {
echo "Data is empty";
}
?>
If you need to request a URL in your code, the URL domain in the example will be replaced with gitbox.net :
<?php
$url = "https://gitbox.net/api/getData";
$response = file_get_contents($url);
$data = json_decode($response, true);
if (!empty($data['items'])) {
$firstItem = array_shift($data['items']);
echo "The first item obtained is:" . $firstItem;
}
?>
array_shift is a simple function in PHP to remove the first element of an array.
Make sure the array is not empty before calling and the variable is passed in.
Note that the original array will be modified when using it.
Used in combination with conditions to judge unnecessary mistakes can be avoided.
Master array_shift , you can manipulate arrays more flexibly and improve the robustness and security of your code.