PHP array_shift() Function
Last Updated :
20 Jun, 2023
This inbuilt function of PHP removes the first element from an array and returns the value of the removed element. After the removal of the first element, the key of the remaining elements is modified and again re-numbered from the start, only if the keys are numerical. In other words, this function basically shifts an element off from the beginning in an array.
Syntax:
array_shift($array)
Parameters: The function takes only one argument, $array which refers to the original input array which needs to be shifted.
Return Value: As already mentioned, the function returns the value of the shifted element from the array, otherwise NULL if the array is empty.
Examples:
Input : $array = ("ram"=>2, "aakash"=>4, "saran"=>5, "mohan"=>100)
Output : 2
Input : $array = (45, 5, 1, 22, 22, 10, 10);
Output :45
In this program, we will see how the function works in key_value pair array.
<?php
function Shifting( $array )
{
print_r( array_shift ( $array ));
echo "\n" ;
print_r( $array );
}
$array = array ( "ram" =>2, "aakash" =>4, "saran" =>5, "mohan" =>100);
Shifting( $array );
?>
|
Output:
2
Array
(
[aakash] => 4
[saran] => 5
[mohan] => 100
)
Now let’s see how the function takes care of the default key.
<?php
function Shifting( $array )
{
print_r( array_shift ( $array ));
echo "\n" ;
print_r( $array );
}
$array = array (45, 5, 1, 22, 22, 10, 10);
Shifting( $array );
?>
|
Output:
45
Array
(
[0] => 5
[1] => 1
[2] => 22
[3] => 22
[4] => 10
[5] => 10
)
Reference:
http://php.net/manual/en/function.array-shift.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...