PHP note (6)-adding elements to an array today I learned how to add an element to a PHP array. Previously, I used the push () function to add: $ arr = array (); array_push ($ arr, el1, el2.... eln );? But there is actually a more PHP note (6)-adding elements to the array
Today I learned how to add an element to a PHP array.
Previously, the push () function was always used to add:
$arr = array();array_push($arr, el1, el2 ... eln);
?
But there is actually a more direct and convenient way:
$arr = array();$arr[] = el1;$arr[] = el2;...$arr[] = eln;
?
Experiments show that the efficiency of the second method is nearly twice higher than that of the first method!
Let's take a look at the following example:
$t = microtime(true); $array = array(); for($i = 0; $i < 10000; $i++) { $array[] = $i; } print microtime(true) - $t; print '
'; $t = microtime(true); $array = array(); for($i = 0; $i < 10000; $i++) { array_push($array, $i); } print microtime(true) - $t;
Run the script and the result is:
? Write Run 1
0.0054171085357666 // array_push
0.0028800964355469 // array []
Run 2
0.0054559707641602 // array_push
0.002892017364502 // array []
Run 3
0.0055501461029053 // array_push
0.0028610229492188 // array []
?
It's really amazing.