![]() |
VOOZH | about |
In PHP, arrays are versatile data structures that can hold multiple values. Often, you may need to add elements to the end of an array, whether it's for building a list, appending data, or other purposes. PHP provides several ways to achieve this. In this article, we will explore different approaches to adding elements to the end of an array in PHP.
Table of Content
The array_push() function is a built-in PHP function that allows you to add one or more elements to the end of an array.
Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 [5] => 60 )
In PHP, you can also add elements to the end of an array by using square brackets [] without specifying an index.
Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 [5] => 60 )
You can also use the += operator to append an associative array to the end of another associative array.
Array ( [fname] => Akash [lname] => Singh [age] => 30 [gender] => male )
The array_merge() function merges one or more arrays, appending elements from subsequent arrays to the end of the first array.
Example:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
The array_splice() function can be used to add elements to the end of an array by specifying the position at which to insert the elements and the number of elements to remove. By setting the position to the current length of the array and the number of elements to remove to 0, we can effectively append elements to the end.
Example:
Array ( [0] => apple [1] => banana [2] => cherry [3] => grape [4] => mango )