PHP array_push() explanation and examples

Saul Goodman September 15, 2019 Loading...

array_push() is a popular function in PHP. It will add one or more elements onto the end of an existing array.

<?php
($my_arr, $value1, $value2, ..., $value1000, ...);

Notes:

  • $value can be number, string, array…
  • array_push() will return the new number of elements in the array.
  • You can add one value or as many as you like at the same time.
  • If you use array_push() to add one element to the array, it’s better to use $array[] = because in that way there is no overhead of calling a function.
  • Your added elements will always have numeric keys even if your array has string keys,
  • array_push() will raise a warning if the first argument is not an array.

Example 1

<?php
$my_arr = ['A', 'B', 'C'];
$d = 'D';
$e = 'E';
array_push($my_arr, $d, $e);
print_r($my_arr);

Here is the result:

Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
    [4] => E
)

Example 2 (add arrays onto the end of an array)

<?php
$my_arr = [
    'name' => 'Donald Trump',
    'job' => 'singer'
];

array_push($my_arr, ['age' => 74], ['networth' => '$4 billions']);

echo '<pre>';
print_r($my_arr);
echo '</pre>';

Here is the result:

Array
(
    [name] => Donald Trump
    [job] => singer
    [0] => Array
        (
            [age] => 74
        )

    [1] => Array
        (
            [networth] => $4 billions
        )

)

Related posts

avatar
Welcome to KINDACODE. Have a nice day and code well!