How to push or insert elements in a PHP array?

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.

This array_push() function updates the original array, and it returns the number of elements after inserting.

<?php
$array = ['PHP', 'C++', 'JavaScript'];

$num_array_el = array_push($array, "Python", "Java");

echo "Number of elements - $num_array_el <pre>";
print_r($array);
echo "</pre>";
Number of elements - 5
Array
(
    [0] => PHP
    [1] => C++
    [2] => JavaScript
    [3] => Python
    [4] => Java
)

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]
)

Leave a Reply

Your email address will not be published. Required fields are marked *