In this tutorial, you will learn how to insert or push elements in a PHP array, and you will also learn how to push with key-value pair.
PHP array_push() Function
With the help of the
array_push() function, you can insert one or more elements in a PHP array at once. But this function does not allow you to insert elements with keys.
array_push(array, value1, value2, value3, ...)
array(required) – The array to which you want to insert elements.
values– The values that are going to be inserted into the array. This parameter is optional, but at least one value is required in PHP versions before 7.3.
array_push() function updates the original array, and it returns the number of elements after inserting.
PHP array push with key-value pair
If you want to push elements in key-value pairs into a PHP array, you need to use the square brackets
<?php $array = ["name" => "John Doe"]; $array["email"] = "[email protected]"; echo "<pre>"; print_r($array); echo "</pre>";
Array ( [name] => John Doe [email] => [email protected] )