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:
- 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
)
- Using
array_push()
function:
Thearray_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.