add an element to the end of an array in php

To add an element to the end of an array in PHP, you can use the [] notation or the array_push() function.

Using the [] notation:

main.php
$myArray = [1, 2, 3];
$myArray[] = 4; // Adds 4 to the end of the array
print_r($myArray); // Outputs Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
148 chars
4 lines

Using the array_push() function:

main.php
$myArray = [1, 2, 3];
array_push($myArray, 4); // Adds 4 to the end of the array
print_r($myArray); // Outputs Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
157 chars
4 lines

related categories

gistlibby LogSnag