up vote 3 down vote favorite
1

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

link|flag

67% accept rate

4 Answers

up vote 9 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);
?>
link|flag
up vote 3 down vote

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';
link|flag
up vote 1 down vote

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

link|flag
up vote 0 down vote

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);
link|flag

Your Answer

get an OpenID
or
never shown

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