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

share|improve this question
2  
$myArray[] = 123; This will be faster than array_push function. It directly adds the value into that array. Function has separate stack for that variables. and it may have that statement inside that function,. – sganesh Mar 12 '10 at 9:32

5 Answers

up vote 12 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

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

share|improve this answer

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.

share|improve this answer

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().

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.