Blog de programación, errores, soluciones

Chose Language:
comments
Author: Admin/Publisher |finished | checked

PHP array_shift function

The PHP function array_shift will remove the first element from the array and return its value. Note that changes to the array are made in the original array, so when we call the array again, it will no longer have its first element.

This function will reset the pointer of the array passed as a parameter after its use
Description / Descripción
array_shift(array &$array): mixed

See the description and note that the array is passed by reference, &$array, which means that this function will work with the original array. In fact, when we pass something by reference, we are passing the memory address of our array.

Sintaxis / Sintax
$deleted_value = array_shift($array);

Parameter

$array – array from which we want to remove the first element.

Returns

mixed – it will return the value of the removed element.

null – in case the array is empty or $array is not an array.

PHP array_shift Examples

In addition to the example provided by php.net, let’s see an example with an associative array first to confirm that there is no difference in the use of the function.

Ejemplo de array_shift
$persona = array(
    "nombre" => "Juan",
    "edad" => 25,
    "ciudad" => "EjemploCity"
);
$value = array_shift($persona);
echo "$value\n";
print_r($persona);
Juan
Array
(
    [edad] => 25
    [ciudad] => EjemploCity
)

Now let’s see the example from php.net:

$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments