How to Add an Element to the End of an Array in PHP?

Problem:

You have an array and you want to add an element to the end of it. But you don’t know the index number of the last element so that you can add the new element next to it.

Solution:

You can do it in few ways. Here are two of those-

Method 1:Using array_push() function

To add an element to the end of an array use array_push() function. As this function treats an array as stack, it adds a new element to the end of the array. See the following example-

<pre>
<?php
$languages = array("c", "c++", "java");
array_push($languages, "php");
print_r($languages);
?>
</pre>

[wpdm_file id=52]

Output:

Array
(    
    [0] => c
    [1] => c++
    [2] => java
    [3] => php
)

In the above example, we added “php” in the $language array to the end.

Note: You can also add more than one element at a time in the array. The following example attempts to add 3 elements at a time.

<pre>
<?php                   
$languages = array("c", "c++", "java");                   
array_push($languages, "php", "asp", "python");                   
print_r($languages);
?>
</pre>

[wpdm_file id=53]

Output:

Array
 (
    [0] => c
    [1] => c++
    [2] => java
    [3] => php
    [4] => asp
    [5] => python
 )

Method 2: Using $array[] = $new_element

You can also push a new item at the end of an array using the following approach-

<pre>
<?php
$languages = array("c", "c++", "java");
$languages[] = "php";
print_r($languages);
?>
</pre>

[wpdm_file id=54]

Output:

Array
 (
    [0] => c
    [1] => c++
    [2] => java
    [3] => php
 )

Note: As this approach directly push the element without any help of a function, this approach is better than the previous one to insert a single element in the array.