How to add elements to an empty array in PHP?

Created by Bart S.Linked to 55m issues across 205 teams


Here's how to add elements to an empty array in PHP:

First, create an empty array:

$cart = array();

To add elements to the array, you can use either the array_push() function or a for loop.

To use array_push(), simply pass the array and the elements you want to add as arguments:

array_push($cart, 13); array_push($cart, 14);

Or, you can use a for loop to add elements to the array:

for($i=0;$i<=5;$i++){ $cart[] = $i; }

Finally, you can print the array to check that the elements have been added:

echo "<pre>"; print_r($cart); echo "</pre>";