In php, we can add items to arrays easily. If you want to add items to the end of an array, you can use the php array_push() function.
$example = array("lion");
array_push($example, "bear", "snake", "horse");
print_r($example);
//Output:
Array
(
[0] => lion
[1] => bear
[2] => snake
[3] => horse
)
If you want to add items at the beginning of an array, you can use the php array_unshift() function.
$example = array("lion");
array_unshift($example, "bear", "snake", "horse");
print_r($example);
//Output:
Array
(
[0] => bear
[1] => snake
[2] => horse
[3] => lion
)
When working with arrays and collections of data in php, it is useful to be able to add or remove items from our data structures easily.
We can easily add to arrays in php.
If you want to add items to the end of an array, we can use the php array_push() function.
array_push() takes an array and elements you want to add to the end of the array, and appends them to the array.
Below is an example of how to use array_push() to add to an array at the end of the array in php.
$example = array("lion");
array_push($example, "bear", "snake", "horse");
print_r($example);
//Output:
Array
(
[0] => lion
[1] => bear
[2] => snake
[3] => horse
)
How to Add Items at Beginning of Array with array_unshift() in php
If you want to prepend items at the beginning of an array, you can use the php array_unshift() function.
array_unshift() takes an array and elements you want to add to the beginning of the array, and prepends them to the array.
Below is an example of how to use array_unshift() to add to an array at the beginning of the array in php.
$example = array("lion");
array_unshift($example, "bear", "snake", "horse");
print_r($example);
//Output:
Array
(
[0] => bear
[1] => snake
[2] => horse
[3] => lion
)
Adding to an Empty Array in php
One example of using the array_push() function is to add to an empty array. As we know, we can add elements to an array with php array_push() function.
Therefore, after initializing an empty array, adding elements is easy.
Below is a simple example in php of creating an empty array and adding three elements to the array.
$emptyArray = [];
print_r($emptyArray);
array_push($emptyArray,"bear","snake","horse");
print_r($emptyArray);
//Output:
Array
(
)
Array
(
[0] => bear
[1] => snake
[2] => horse
)
Hopefully this article has been useful for you to learn how to use php to add to arrays.