Advertisement
Advertisement


How to add elements to an empty array in PHP?


Question

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)?

2014/04/14
1
505
4/14/2014 8:20:09 AM

Accepted Answer

Both array_push and the method you described will work.

$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc

//Above is correct. but below one is for further understanding
$cart = array();
for($i=0;$i<=5;$i++){
    $cart[] = $i;  
}
echo "<pre>";
print_r($cart);
echo "</pre>";

Is the same as:

<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);

// Or 
$cart = array();
array_push($cart, 13, 14);
?>
2018/11/22
824
11/22/2018 8:58:19 AM

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';
2015/07/31

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

$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
2018/05/05

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);
2009/03/24

$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>";
2019/10/23

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

$arr1 = $arr1 + $arr2;

(see source)

2017/05/23

Source: https://stackoverflow.com/questions/676677
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]