tags:

views:

3760

answers:

4

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

+1  A: 

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

Assaf Lavie
A: 

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
+9  A: 

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);
?>
Bart S.
+3  A: 

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