Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is quicker to use array_keys() in a foreach statemnt or set a value variable that's never used?

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';
}
like image 682
joachim Avatar asked Jan 11 '12 15:01

joachim


People also ask

What is PHP function array_keys () used for?

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.

Which is faster while or foreach?

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.

Which is faster for or foreach in PHP?

In short: foreach is faster than foreach with reference.

What is key in foreach?

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.


2 Answers

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

like image 160
Rocket Hazmat Avatar answered Sep 26 '22 00:09

Rocket Hazmat


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

like image 32
Jason McCreary Avatar answered Sep 22 '22 00:09

Jason McCreary