552

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
AquinasTub
  • 7,345
  • 6
  • 20
  • 14

9 Answers9

894

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);
?>
Yoram de Langen
  • 4,825
  • 2
  • 21
  • 30
Bart S.
  • 9,796
  • 1
  • 17
  • 26
  • 201
    As stated in the PHP documentation, if you're only pushing a single element every time (like in a loop) or a single element once, it's best to use the `$cart[] = 13` method not only because it's less characters to do the same operation, but it also doesn't impose the performance overhead of a function call, which array_push() would. Edit: But, great answer. Effectively the same, and majority of uses won't even notice a performance difference, but helps to know those nuances. – Mattygabe Jan 15 '11 at 05:10
  • 76
    Is it just me or does the `$cart[]=...` syntax, at first glance, look like a variable assignment and not an implicit array_push? – Brad Hein Feb 05 '14 at 16:36
  • 7
    It definitely does to me. I wouldn't mind an explanation of why its **not** an assignment. – limeandcoconut May 20 '14 at 04:05
  • 4
    $cart[] = 13; is faster. has less characters and looks better. – Gal Bracha Jul 28 '14 at 06:54
  • What is this alternate method? Is that a secret method? Syntactical overload? – Alper Jan 12 '16 at 13:37
  • 25
    I'll just offer my alternative viewpoint that it's VERY confusing for other language programmers to read the syntax of cart[] =..., I've got experience with a lot of languages and I'd never guess that's what it does. – Erti-Chris Eelmaa Oct 13 '16 at 18:02
  • Just to add on to what @Mattygabe said about the shorthand - the element can be any object that PHP is happy to put into an array. This is probably stating the obvious, but I figured I'll add that in here too. – Aaron Feb 01 '17 at 13:49
  • @BrassApparatus If is an assignment, you are assigning to the new last element of this array. Did you mean a "plain" assignment? Well, it does have the indexer operator `[]` ? – AturSams May 03 '17 at 10:16
  • @Erti-ChrisEelmaa It wouldn't hurt if other languages picket it up. Is it better in python: `a[len(a):] = [newVal] `? – AturSams May 03 '17 at 10:27
  • Mattygabe's opinion could be doubtful, because optimization is required when it really pays off and not in every case (as per Steve McConnell). Readability and non-frustrainability of code is often much more important. Experimental facts from tests in loop are needed to say that `=` should be prefered to `array_push`. – Zon Aug 02 '18 at 12:37
  • 2
    @wolfdawn I don't disagree with your idea about other languages picking this syntax up, but in python you can simply call `a.append(new_val)` or `a.push(new_val)` for a list. – dmcoding Feb 08 '19 at 20:09
  • As an array can never be used for print with [ ], everytime you use like that, I mean empty, it means add to specified array. If you put a value, like [$x] or [3] than you specify a key, to read from array. Is that simple. – Lucian Minea Sep 13 '19 at 13:11
  • @AturSams I would use array_push any time (for readability) over the 2nd syntax (for micro optimization). In all languages I know, including PHP itself, array[index] = value; is an assignment. How come removing the index means adding new value at the end of the array? PHP syntax is weird sometimes... – Daniel Wu Feb 02 '21 at 03:39
82

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';
kamal pal
  • 4,049
  • 5
  • 22
  • 39
OIS
  • 9,161
  • 1
  • 29
  • 41
  • 13
    "If you're adding multiple values to an array in a loop, it's faster to use array_push than repeated [] = statements" http://www.php.net/manual/en/function.array-push.php#84959 – Ollie Glass Dec 18 '10 at 17:15
  • 3
    Absolutely correct if your use-case is adding a single item or items one at a time. If all values are known at the same time, it's probably best just to use the array_push notation depending on how many items must be added the extra characters from re-typing the array name each time may be more of a performance hindrance than the function call over-head. As always, judgment should be exercised when choosing. Good answers! – Mattygabe Jan 15 '11 at 05:13
  • 2
    This answer is the most complete. – Lokiare May 24 '18 at 16:19
  • 1) `array_push()` has a *return value*, whereas the others do not. Perhaps this is the/one reason for its overhead? It seems to be a consensus to use the other methods, unless you need that return value. 2) *If you need elements to be added to the **end** of the array*, use either `array_push()` or `+=` method of concatenation (not shown in this answer), or `$cart[] = 13` methods. Using the named/numeric key method (`$cart[4] = $object` and $cart['key'] = 'test'` methods do not *guarantee* the element will be added to the *end* of the array, only that it will be *in* the array. – SherylHohman Jun 30 '20 at 23:40
  • @SherylHohman: This $cart[] = will add values to the end of the array. – OIS Sep 11 '20 at 05:48
14

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

$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
fico7489
  • 6,416
  • 5
  • 44
  • 77
11

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);
andi
  • 13,928
  • 9
  • 44
  • 46
5
$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>";
unpluggeDloop
  • 71
  • 1
  • 3
  • $cart[] = $i; - that part of code add elements to array ----> $cart = [$i]; - this will pass compiler but you will not get what you want – unpluggeDloop Oct 28 '19 at 12:08
3

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

$arr1 = $arr1 + $arr2;

(see source)

Community
  • 1
  • 1
T.Todua
  • 44,747
  • 17
  • 195
  • 185
1
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"isuru.eshan@gmail.com"));
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>";
}
-1

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';
-1

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>";
showdev
  • 25,529
  • 35
  • 47
  • 67