Adding Array Items

There are a few different ways to add items to arrays in PHP, depending on whether the array is indexed or associative, and whether you're adding one or multiple items.

1. Adding a single item to an indexed array

Just use the [] syntax — PHP will add the item to the next available index:

$fruits = ["Apple", "Banana", "Cherry"];
$fruits[] = "Orange";

2. Adding a single item to an associative array

Use brackets [] with the key name:

$cars = ["brand" => "Ford", "model" => "Mustang"];
$cars["color"] = "Red";

3. Adding multiple items to an indexed array

Use array_push(), passing all new items:

$fruits = ["Apple", "Banana", "Cherry"];
array_push($fruits, "Orange", "Kiwi", "Lemon");

4. Adding multiple items to an associative array

Use the += operator to merge arrays:

$cars = ["brand" => "Ford", "model" => "Mustang"];
$cars += ["color" => "red", "year" => 1964];

This keeps the existing keys and adds new ones.