[php] How to add elements to an empty array in PHP?

If I define an array in PHP such as (I don't define its size):

$cart = array();

Do I simply add elements to it using the following?

$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;

Don't arrays in PHP have an add method, for example, cart.add(13)?

This question is related to php arrays variables

The answer is


REMEMBER, this method overwrites first array, so use only when you are sure!

$arr1 = $arr1 + $arr2;

(see source)


Based on my experience, solution which is fine(the best) when keys are not important:

$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;

$cart = array();
$cart[] = 11;
$cart[] = 15;

// etc

//Above is correct. but below one is for further understanding

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

//if you write $cart = [$i]; you will only take last $i value as first element in array.

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

$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"[email protected]"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";

//OR

$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}

You can use array_push. It adds the elements to the end of the array, like in a stack.

You could have also done it like this:

$cart = array(13, "foo", $obj);

When one wants elements to be added with zero-based element indexing, I guess this will work as well:

// adding elements to an array with zero-based index
$matrix= array();
$matrix[count($matrix)]= 'element 1';
$matrix[count($matrix)]= 'element 2';
...
$matrix[count($matrix)]= 'element N';

It's better to not use array_push and just use what you suggested. The functions just add overhead.

//We don't need to define the array, but in many cases it's the best solution.
$cart = array();

//Automatic new integer key higher than the highest 
//existing integer key in the array, starts at 0.
$cart[] = 13;
$cart[] = 'text';

//Numeric key
$cart[4] = $object;

//Text key (assoc)
$cart['key'] = 'test';

Both array_push and the method you described will work.

$customArray = array();
$customArray[] = 20;
$customArray[] = 21;

Above is correct, but below one is for further understanding

$customArray = array();
for($i=0;$i<=12;$i++){
    $cart[] = $i;  
}
echo "<pre>";
print_r($customArray);
echo "</pre>";

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?