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