To add an element to the end of an array in PHP, you can use the array_push()
function or simply use the []
syntax. Here are two methods for adding an element to the end of an array:
array_push()
$array = [1, 2, 3]; // Existing array
$newElement = 4; // Element to be added
array_push($array, $newElement); // Adding element to the array
print_r($array); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
[]
syntax$array = [1, 2, 3]; // Existing array
$newElement = 4; // Element to be added
$array[] = $newElement; // Adding element to the array
print_r($array); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Both methods will add the element to the end of the array.