What\'s better to use in PHP for appending an array member,
$array[] = $value;
or
array_push($array, $value);
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
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.
Word on the street is that [] is faster because no overhead for the function call. Plus, no one really likes PHP's array functions...
"Is it...haystack, needle....or is it needle haystack...ah, f*** it...[] = "
Since "array_push" is a function and it called multiple times when it is inside the loop so it will allocate a memory into the stack. But when we are using $array[] = $value then we just assigning value to array.
I just wan't to add : int array_push(...)
return
the new number of elements in the array (php doc). which can be useful and more compact than $myArray[] = ...; $total = count($myArray);
.
Also array_push(...)
is meaningful when variable is used as stack.
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.