PHP array_push examples

Last updated on February 22, 2022 A Goodman Loading... Post a comment

The array_push function in PHP pushes the input variables onto the end of the given array. Note that the input variables can be string, number, array…

Example 1

Code:

<?php
$arr = ['Dog', 'Cat', 'Monkey', 'Chicken', 'Dragon', 'Alligator'];

array_push($arr, 'Dolphin', 'Donkey', 'Leopard');

// Printing the output
echo '<pre>';
print_r($arr);
echo '</pre>';
?>

Output:

Array
(
    [0] => Dog
    [1] => Cat
    [2] => Monkey
    [3] => Chicken
    [4] => Dragon
    [5] => Alligator
    [6] => Dolphin
    [7] => Donkey
    [8] => Leopard
)

Example 2

Code:

<?php
$arr = [1, 2, 3, 4, 5];
array_push($arr, [6, 7], [8, 9, 10], 'A', 'B', 'C');

echo '<pre>';
print_r($arr);
echo '</pre>';
?>

Output:

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

    [6] => Array
        (
            [0] => 8
            [1] => 9
            [2] => 10
        )

    [7] => A
    [8] => B
    [9] => C
)

Further reading:

Happy coding and have a nice day.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles