Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

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

Don't arrays in PHP have a add method, i.e. cart.add(13)?

share|improve this question

4 Answers

up vote 121 down vote accepted

Both array_push and the method you described will work.

<?php
$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc
?>

Is the same as:

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

// Or 
$cart = array();
array_push($cart, 13, 14);
?>
share|improve this answer
24  
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 5:10

Its better to not use array_push and just use what you suggested. The functions just add overhead.

//dont need to define the array, but in many cases its the best solution.
$cart = array();

//automatic new integer key higher then 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';
share|improve this answer
3  
"If you're adding multiple values to an array in a loop, it's faster to use array_push than repeated [] = statements" php.net/manual/en/function.array-push.php#84959 – Ollie Glass Dec 18 '10 at 17:15
1  
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 5:13

It's called array_push: http://il.php.net/function.array-push

share|improve this answer

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.