Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP array_shift() Function

PHP array_shift() Function

PHP Array ReferenceComplete PHP Array Reference Manual

Example

Delete the first element (red) of an array and return the removed element:

" red " , " b " => " green " , " c " => " blue " ) ; echo array_shift ( $a ) ; print_r ( $a ) ; ?>

Run Example »


Definition and Usage

The array_shift() function removes the first element from an array and returns the removed element.

**Note:** If the keys are numeric, all elements will get new keys starting from 0 and increasing by 1 (see the example below).


Syntax

array_shift(

array

)

Parameters Description
array Required. Specifies the array.

Technical Details

Return Value: Returns the value of the removed element, or NULL if the array is empty.
PHP Version: 4+

More examples

Example 1

Using numeric keys, all elements will get new keys:

" red " , 1 => " green " , 2 => " blue " ) ; echo array_shift ( $a ) ; print_r ( $a ) ; ?>

Run Example »

To preserve the numeric key indexes, you can use the following method:

Example

1 , '2' => 2 , '3' => '3' ) ; function array_kshift ( & $arr ) {   list ( $k ) = array_keys ( $arr ) ;   $r   = array ( $k => $arr [ $k ] ) ;   unset ( $arr [ $k ] ) ;   return $r ; } array_kshift ( $arr ) ; print_r ( $arr ) ; ?>

The output of the above example is:

Array
(
    [2] => 2
    [3] => 3
)

More information:PHP - Remove the First Element of an Array


PHP Array ReferenceComplete PHP Array Reference Manual