views:

223

answers:

5

If I understood properly you can add value to an array by using :

$myArray[] = 123;

or

array_push($myArray, 123);

Is one cleaner/faster then the other one ?

+8  A: 

From the php docs for array_push:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Benedict Cohen
A: 

A simple $myarray[] declaration will be quicker as you are just pushing an item onto the stack of items due to the lack of overhead that a function would bring.

seacode
+1  A: 

Second one is a function call so generally it should be slower than using core array-access features. But I think even one database query within your script will outweight 1.000.000 calls to array_push().

Stefan Gehrig
+6  A: 

One difference is that you can call array_push() with more than two parameters, i.e. you can push more than one element at a time to an array.

$myArray = array();
array_push($myArray, 1,2,3,4);
echo join(',', $myArray);

prints 1,2,3,4

VolkerK
+2  A: 

The main use of array_push() is that you can push multiple values onto the end of the array.

It says in the documentation:

If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Inspire