Append to array PHP

How to add more data to an array in PHP

Posted by Ervin Adams on August 2, 2022

Append to array PHP

How to add more data to an array in PHP

Posted by Ervin Adams on August 2, 2022

Here are some ways that you can add more data to an array in PHP

1. Use array_push()

array_push() allows you to add new items to the end of the array

Examples below:

Add  an item

$superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
array_push($superCars, "Aston Martin");
var_dump($superCars);

Add multiple items

$superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
array_push($superCars, "Aston Martin", "Bugatti");
var_dump($superCars);

2. Use array_shift()

array_shift() allows you to add new items at the start of the array.

Example below:

Add an item

$superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
array_unshift($superCars, "Aston Martin");
var_dump($superCars);

Add multiple items

$superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
array_unshift($superCars, "Aston Martin", "Bugatti");
var_dump($superCars);

3. Add item directly

Using $superCars = [] will add items directly in the array. It is suggested that if you are just adding a few items without much complications this technique will reduce overhead, hence increase performance. 

Add an item

$superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
$superCars[] = "Aston Martin";
var_dump($superCars);

Add multiple items

$superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
$superCars[] = "Aston Martin";
$superCars[] = "Bugatti";
var_dump($superCars);