Suppose I want to iterate over an array and either I never look at the values, or I am setting things in them, so I only want the keys. Which is quicker:
// Set a variable each iteration which is unused.
foreach ($array as $key => $value) {
$array[$key]['foo'] = 'bar';
}
// Call array_keys() before iterating.
foreach (array_keys($array) as $key) {
$array[$key]['foo'] = 'bar';
}
array_keys() function in PHP The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.
Deductions. This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
In short: foreach is faster than foreach with reference.
In every loop the current element's key is assigned to $key and the internal array pointer is advanced by one and the process continue to reach the last array element. Example -1 : In the following example, we define an array with five elements and later we use foreach to access array element's value.
I think this would also work, and may be quicker:
foreach ($array as &$value) {
$value['foo'] = 'bar';
}
UPDATE: I did a little test, and it seems this is faster. http://codepad.org/WI7Mtp8K
Leaving aside that the second example is contrived. Meaning, as Ashley Banks noted, why would you be doing this?
The first example would be more performant of the two. The second has the overhead of the additional function call to array_keys()
.
Check out the PHP Benchmark for additional performance tests. When in doubt, benchmark it yourself with microtime()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With