Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Insert and Remove value from begining of an array

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 184
    Comment on it

    This article demonstrate two predefined functions of PHP to add and remove values from begining of an array.

    1.array_shift(): This function removes first element of an array and returns the removed value. The numeric keys of array are automatically adjusted to start from 0 and keys as string will not be changed. Syntax:

    array_shift($array);

    Example:

    $array = array(1, 2, 3, 4, 5);
    echo "Array before array_shift : ";
    print_r($array);
    $value = array_shift($array);
    echo "Removed Value : ".$value;
    echo "Array after array_shift : ";
    print_r($array);
    

    Output:

    Array before array_shift :
    
    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
    )
    
    Removed Value : 1
    
    Array after array_shift :
    
    Array
    (
        [0] => 2
        [1] => 3
        [2] => 4
        [3] => 5
    )
    

    2.array_unshift():This function used to insert one or more values in the beginning of an array.The numeric keys of array are automatically adjusted according to new elements inserted in beginning and keys as string will not be changed.

    Syntax:

    array_unshift($array,$value1,$value2,......);

    Example:

    $array = array(2, 3, 4, 5);
    echo "Array before unshift : ";
    print_r($array);
    array_unshift($array, 0, 1);
    echo "Array after unshift : ";
    print_r($array);
    

    Output:

    Array before unshift : 
    Array
    (
        [0] => 3
        [1] => 4
        [2] => 5
    )
    
    Array after unshift : 
    Array
    (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 4
        [4] => 5
    )
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: