Javatpoint Logo
Javatpoint Logo

PHP append to array

Not only in PHP, but also in other programming languages, appending or adding an element to an array is a frequent approach. In PHP, however, there are a few techniques for adding elements to an array. These approaches differ depending on their intended usage. You can use one of the two methods to add an element to the end of the array. If you want to add elements to the beginning of an array, you can use the array unshift method.

One of the most widely used PHP add to array methods is the square bracket method. Most programmers prefer using this strategy because of its efficiency. It adds to an array without the overhead of calling a function, as opposed to the other ways. However, there is a drawback in that it can only add one argument at a time.

Syntax of Square Bracket method

Here array refers to the original array you are looking to append.

elementis the value you are looking to add to the array.



array(9) { [0]=> string(7) "English" [1]=> string(7) "Persian" [2]=> string(6) "French" [3]=> string(7) "Russian" [4]=> string(7) "Mexican" [5]=> string(7) "Spanish" [6]=> string(7) "Italian" [7]=> string(5) "Dutch" [8]=> string(5) "Hindi" }

Code 2:


Printing the list of fruits using PHP
array(12) { [0]=> string(5) "Apple" [1]=> string(5) "Mango" [2]=> string(9) "Blueberry" [3]=> string(6) "Cherry" [4]=> string(11) "Water Melon" [5]=> string(6) "Orange" [6]=> string(6) "Banana" [7]=> string(4) "Kiwi" [8]=> string(12) "Dragon Fruit" [9]=> string(11) "Green Apple" [10]=> string(10) "Strawberry" [11]=> string(5) "Peach" }

As you can see, the code above may be used to add to an array in PHP. However, despite its quickness, utilizing this method to add more than one element would be inconvenient.

Using the array push technique is as follows:

Another built-in method in PHP that can be used to add to arrays is array pushis. This function can be used to simultaneously add several elements to an array.

Syntax of array_push


array - This argument is required and defines the array to which you want to attach values.

value1 - The value you want to include in the array

Values of Return

The array push function returns the array's element count.



array(6) { [0]=> string(10) "Javascript" [1]=> string(6) "Python" [2]=> string(3) "C++" [3]=> string(3) "PHP" [4]=> string(4) "HTML" [5]=> string(3) "CSS" }



Array append exam[le in PHP with array_push method.
array(10) { [0]=> string(11) "Banyan Tree" [1]=> string(10) "Eucalyptus" [2]=> string(8) "Mahagony" [3]=> string(9) "Cork Tree" [4]=> string(10) "Cedar Tree" [5]=> string(5) "Hazel" [6]=> string(10) "Common Ash" [7]=> string(8) "Hawthorn" [8]=> string(15) "Juglans cinerea" [9]=> string(20) "Robinia pseudoacacia" }

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA