How To Use Array Push Function With Example In PHP

admin_img Posted By Bajarangi soft , Posted On 18-09-2020

when you already created array with certain elements and if you want to add one or more values to that array, then you need to use the array_push() function, which inserts one or more elements to the end of an array and also length of the array increases by the number of variables pushed to array and even if your array has string keys, you can also add numeric keys.

update multiple values to array

PHP array_push() Function

The array_push() function add one or more elements to the end of an array.

Syntax of array_push function and Usage:

array_push(array, value1, value2, ...)


Parameter Description:

array    -> its required and for which array we need to add elements for that array is specified here.
value1   -> its optional because the elements which are passing to array
value2   -> its optional. Specifies the value to add


1.Create array.

$array=array("a"=>"PHP","b"=>"Python","c"=>"embedded C");


2.Use array_push()  function to add elements in to $array.
 
array_push($array,"JAVA","C#");
 

3.Display $array using print_r function or you can also use foreach to display array elements.
 

print_r($array);

 

4.Complete code of updating multiple values in to array.
 

<!DOCTYPE html>
<html>
<head>
    <title>Update multiple values to an array </title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>Update multiple values to an array in PHP</h1>
    </div>
    <br>
    <h2></h2>
    <div class="well">
        <?php
        $array=array("a"=>"PHP","b"=>"Python","c"=>"embedded C");
        array_push($array,"JAVA","C#");
        print_r($array);
        foreach ($array as $ar){
            echo "<h1>".$ar."</h1>";
        }
        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post