In the PHP manual, (array_push) says..
If you use array_push() to add one element to the array it\'s better to use $array[]
I know this is an old answer but it might be helpful for others to know that another difference between the two is that if you have to add more than 2/3 values per loop to an array it's faster to use:
for($i = 0; $i < 10; $i++){
array_push($arr, $i, $i*2, $i*3, $i*4, ...)
}
instead of:
for($i = 0; $i < 10; $i++){
$arr[] = $i;
$arr[] = $i*2;
$arr[] = $i*3;
$arr[] = $i*4;
...
}
edit- Forgot to close the bracket for the for
conditional
explain: 1.the first one declare the variable in array.
2.the second array_push method is used to push the string in the array variable.
3.finally it will print the result.
4.the second method is directly store the string in the array.
5.the data is printed in the array values in using print_r method.
this two are same
No one said, but array_push only pushes a element to the END OF THE ARRAY, where $array[index] can insert a value at any given index. Big difference.
You should always use $array[]
if possible because as the box states there is no overhead for the function call. Thus it is a bit faster than the function call.
both are the same, but array_push makes a loop in it's parameter which is an array and perform $array[]=$element
The difference is in the line below to "because in that way there is no overhead of calling a function."
array_push()
will raise a warning if the first argument is not an array. This differs from the$var[]
behaviour where a new array is created.