PHP Add to Array | Push Value to Array PHP – array_push()
Posted on: August 07, 2020 by Amilcar Paco
In this tutorial we’ll learn how to add one or more elements onto the end of array.
Contents
Requirements
- PHP running on your computer
- Basic knowledge of PHP
- Text Editor
Definition
array_push()
is a PHP function that is used to add one or more elements onto the end of an array. The length of array increases by the number of variables pushed.
Your added elements will always have numeric keys, even if the array itself has string keys.
Syntax
array_push(array, value1, value2, ...)
Description
- array is a required value. Specifies an array.
- value1 is an opcional value. Specifies the value/element to add.
- value2 is an opcional value. Specifies the value/element to add.
- value1 is a required value in PHP versions before 7.3.
Usage
Open a php file and create an array of fruits.
<?php
$fruit = array('banana', 'orange');
print_r($fruit);
Output
Array
(
[0] => banana
[1] => orange
)
Let’s add some elements onto the end of fruit array.
<?php
$fruit = array('banana', 'orange');
// adding elements using array_push
array_push($fruit, 'mango', 'tangerine');
print_r($fruit);
Output
Array
(
[0] => banana
[1] => orange
[2] => mango
[3] => tangerine
)
We can change the fruit array keys to an array with string keys and see what happens:
<?php
// change the keys to string keys
$fruit = array('a'=>'banana', 'b'=>'orange');
// adding elements using array_push
array_push($fruit, 'mango', 'tangerine');
print_r($fruit);
Output
Array
(
[a] => banana
[b] => orange
[0] => mango
[1] => tangerine
)
We see that every added elements will always have numeric keys.
Conclusion
Now you are able to add one or more elements onto the end of every array.
Thanks for reading.
Share on social media
//