Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach that returns keys only

Theoretical question that perhaps does not make any sense but still, maybe there is a clever answer.

I want to iterate through array and get its keys and to something with them. A quick example of what I do:

foreach($array as $key => $value) {     $other_array[$key] = 'something'; } 

Now, PHP Mess Detector screams that $value is unused in this scope. Therefore I was thinking that perhaps this is not the best way to access keys of my array.

Any idea how to do it without unnecessarily taking out values out of my array? Does it have any significant performance impact ... or perhaps I am just being paranoid and should carry on without wasting anyone's time with stupid questions :).

like image 926
RandomWhiteTrash Avatar asked Sep 10 '12 07:09

RandomWhiteTrash


People also ask

Does foreach mutate array?

forEach() does not mutate the array on which it is called.


1 Answers

You could do something like this

foreach(array_keys($array) as $key) {  // do your stuff } 

That would make the foreach iterate over an array consisting of the keys from your array instead of the actual array. Note that it's probably not better from a performance standpoint though.

like image 64
inquam Avatar answered Oct 02 '22 16:10

inquam