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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 202
    Comment on it

    This article demonstrate how to add and remove value on start and end of an array using predefined functions of PHP. The four important array functions in PHP are :

    1. array_push() : This function is used to add one or more values to the end of an array.

    Syntax :
    array_push($array, $value1, $value2,.......);

    Example:

    $colors = array("green","blue","pink");
    echo "Array before array_push : ";
    print_r($colors);
    array_push($colors,"red","black");
    print_r($colors);
    

    Output :

    Array before array_push :
    Array
    (
        [0] => green
        [1] => blue
        [2] => pink
    )
    Array after array_push :
    Array
    (
        [0] => green
        [1] => blue
        [2] => pink
        [3] => red
        [4] => black
    )
    

    2. array_pop() : This function is used to remove the last element from array and returns the removed value.

    Syntax: array_pop($array);

    Example :

    $colors = array("green","blue","pink","red");
    echo "Array before array_pop : ";
    print_r($colors);
    $value = array_pop($colors);
    echo "Removed Value : ".$value;
    echo "Array after array_pop : ";
    print_r($colors);
    

    Output :

    Array before array_pop :
    Array
    (
        [0] => green
        [1] => blue
        [2] => pink
        [3] => red
    )
    Removed Value : red
    Array after array_pop :
    Array
    (
        [0] => green
        [1] => blue
        [2] => pink
    )
    

 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: