Home PHP How to add an element to the end of an array?

How to add an element to the end of an array?

Author

Date

Category

To add an element to the end of an array in PHP, you can use the [] notation or the array_push() function. Here’s how you can do it:

  1. Using [] notation:
    You can use the square bracket notation with empty brackets [] to append a new element to the end of an array. This method is commonly used and provides a concise way to add elements.
PHP
$fruits = ["apple", "banana", "orange"];
$fruits[] = "mango"; // Add "mango" to the end of the array

print_r($fruits);


Output:

PHP
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => mango
)
  1. Using array_push() function:
    The array_push() function allows you to add one or more elements to the end of an array. It takes the array as the first parameter, followed by the element(s) to be added.
PHP
$fruits = ["apple", "banana", "orange"];
array_push($fruits, "mango"); // Add "mango" to the end of the array

print_r($fruits);


Output:

PHP
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => mango
)


Both methods will result in adding the new element to the end of the array. Choose the method that suits your coding style and requirements.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subhash Shipu

PHP Expert

Hey there! I'm a PHP geek on a mission to blog my way through the coding chaos. When I'm not chasing semicolons, I'm busy cuddling my pet Coco, who thinks debugging means chasing her own tail. Join the fun!

Subscribe

Recent posts