To add a element to an array in PHP, you can use the array_push()
function or the square bracket notation []
.
Here’s an example using array_push()
:
$myArray = array('apple', 'banana', 'orange');
$newElement = 'pear';
array_push($myArray, $newElement);
print_r($myArray);
This would output:
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => pear
)
Alternatively, you can use square bracket notation:
$myArray = array('apple', 'banana', 'orange');
$newElement = 'pear';
$myArray[] = $newElement;
print_r($myArray);
This would also output:
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => pear
)
Both approaches achieve the same result, so you can choose the one that you find more readable or convenient.