Push a Value on an Array

suggest change

There are two ways to push an element to an array: array_push and $array[] =


The array_push is used like this:

$array = [1,2,3];
$newArraySize = array_push($array, 5, 6); // The method returns the new size of the array
print_r($array); // Array is passed by reference, therefore the original array is modified to contain the new elements

This code will print:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 6
)

$array[] = is used like this:

$array = [1,2,3];
$array[] = 5;
$array[] = 6;
print_r($array);

This code will print:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 5
    [4] => 6
)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents