PHP append to array - How to add elements to an array

To append an element to an array, you can use either the array_push() function or the index assignment syntax.

The array_push() function accepts at least two arguments:

  • The $array you want to add new elements into
  • The $values you want to append to the $array

You can pass as many $values that you want to append to the array.

Hereโ€™s an example of the array_push() function in action:

<?php

$arr = [1, 2];

// ๐Ÿ‘‡ append to array
array_push($arr, 3, 4, 5);

print_r($arr);
// ๐Ÿ‘‡ output:
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 4
//     [4] => 5
// )

The array_push() function will add new array elements to the end of the array.

Alternatively, you can also use the array index assignment syntax in the form of $arr[] = to append an element to the array.

Consider the code example below:

<?php

$arr = [1, 2];

// ๐Ÿ‘‡ append to array
$arr[] = 3;
$arr[] = 4;
$arr[] = 5;

print_r($arr);
// ๐Ÿ‘‡ output:
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 4
//     [4] => 5
// )

As you can see, both the array_push() function and the index assignment syntax produce the same result.

Which method should you use to append elements to an array?

When you need to add a single element to your array, itโ€™s better to use the index assignment syntax to eliminate the overhead of calling a function.

But if you have several elements to add to an existing array, then you should use the array_push() function. Using the index assignment syntax causes you to repeat your code as seen above.

And now youโ€™ve learned how to append elements to an array. Nice! ๐Ÿ‘

Take your skills to the next level โšก๏ธ

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.