PHP

PHP array_push

PHP array_push is a function in PHP that is used to add values to an array. 

If you want to add values in an array and you don’t want to change the existing array so you can take help from PHP array_push Function.

Let’s see how it works.

Syntax – PHP array_push

array_push(array, value1, value2,….)

Example 1

<?php

$color=array("red","yellow");

array_push($color,"blue","purple");

print_r($color);

?>

In the above example, we declare an array for adding more values to the array we use the PHP array_push method. After that in the array_push function we mention the array name and pass the values which we want to add to that array and then we print the array.

Let’s check the result.

Output

Array ( [0] => red [1] => yellow [2] => blue [3] => purple )

As you can see in the output the values which we added through array_push function are showing at the end of the array. We can push multiple values as you can see in the next example.

Example 2

<?php

$color=array("red","yellow");

array_push($color,"blue","purple","green","white","orange");

print_r($color);

?>

Output

Array ( [0] => red [1] => yellow [2] => blue [3] => purple [4] => green [5] => white [6] => orange )

As you can see all the values which we pushed through the array_push function are showing at the end of the array.

Let’s try another example.

Example 3

<?php

$color=array("a"=>"red","b"=>"yellow");

array_push($color,"blue","purple");

print_r($color);

?>

In the above example, we declare an associative array then by using the array_push method we pushed 2 values in that array let’s check the result.

Output

Array ( [a] => red [b] => yellow [0] => blue [1] => purple )

As you can see the values which we pushed are showing at the end of the array.

Conclusion

In this tutorial, we talk about the PHP array_push function, see the definition, and discuss some examples using the array_push method.

Suggested Articles:

Leave a Comment