PHP array_push() Function

What is PHP array_push() Function?

If you want to add one or more elements to the end of an array, use array_push() function.

Syntax:

array_push(array, value1, value2, …)

Parameters:

The Function has 1 required parameter and 1 or more optional parameters-

array (Required): The input array

value1, value2,… (Optional): It specifies one or more elements (values) that you want to add. Values are separated by comma. As it is an optional parameter, if you omit this, PHP will not throw any error. See example 2.

Return Values:

It doesn’t return the modified array, but, it adds the elements that you supplied to the function to the end of the input array. The function returns the number of elements in the modified array. See example 4.

Examples:

Example 1:

<pre>
<?php
$language = ["PHP", "Python", "Java"];
array_push($language, "HTML", “CSS”);
print_r($language);
?>
</pre>

Output:

Array
(
[0] => PHP
[1] => Python
[2] => Java
[3] => HTML
[4] => CSS
)

Explanation:

CODE GOES HERE………

Example 2:

<pre>
<?php
$language = ["PHP", "Python", "Java"];
array_push($language);
print_r($language);
?>
</pre>

Output:

Array
(
[0] => PHP
[1] => Python
[2] => Java
)

Example 3:

<pre>
<?php
$language = ["PHP", "Python", "Java"];
$language[] = "HTML";
print_r($language);
?>
</pre>

Output:

Array
(
[0] => PHP
[1] => Python
[2] => Java
[3] => HTML
)

Example 4:

<?php
$language = ["One" => "PHP","Two" =>  "Python","Three" =>  "Java"];
$element_number = array_push($language, "HTML", "CSS");
echo "After running array_push() function, the array now has $element_number elements.";
?>

Output:

After running array_push() function, the array now has 5 elements.

Alternative to the array_push() Function:

If you want to add just one element to the end of an array, use the following way. In fact, this better method as this doesn’t require calling an extra function. See example 3.

$array = $value;

Notes on array_push() Function:

The keys of the newly added elements always have numeric keys.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP array_push() Function

The array_push() function is a built-in PHP function and part of the PHP’s array functions. You can easily add new to any array with this function.

Reference: