OneBite.Dev - Coding blog in a bite size

Insert An Element At The End Of An Array In PHP

Code snippet for how to Insert An Element At The End Of An Array In PHP with sample and detail explanation

Managing arrays effectively in PHP can be an important facet of programming. This article will guide you through how to easily insert an element at the end of an array in PHP.

Code snippet: Inserting an Element

$fruits = array("apple", "banana", "cherry");
array_push($fruits, "durian");
print_r($fruits);

Code Explanation: Inserting an Element

Let’s break down our code piece by piece.

The first line of our script initializes an array we’ve named $fruits, and it contains three string elements — “apple”, “banana”, “cherry”.

$fruits = array("apple", "banana", "cherry");

The second line of code is where the magic happens. This is where we use the array_push function to insert another fruit, “durian”, at the end of our existing $fruits array.

array_push($fruits, "durian");

The array_push function, as the name implies, “pushes” or inserts an element or elements at the end of an array. This function takes at least two parameters:

  1. The first argument is the array you want to add an element to — in our case, the $fruits array.
  2. The next argument(s) is/are the element(s) you want to add. You can add any type of elements, from strings and integers to other arrays. In our case, we’ve just added one new string, “durian”.

Our last line of code prints the updated $fruits array using the print_r function.

print_r($fruits);

When you run the script, the output will be:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
    [3] => durian
)

You can see that “durian” has been added to the end of our $fruits array successfully. This shows that our array_push function indeed adds a new element to the end of the array as needed.

Feel free to practice with other array elements or even with multiple elements at once to really get the hang of how array_push function works!

php