I can't really help you with the performance bit, only tell you to wrap them in microtime()
tags and see which one performs better for you. Systems are slightly different. The one suggestion I can give you is to remove array_keys()
from your code.
!!UPDATE!!
If you were following Corbin and my argument below, then I finally have an answer for you. I was getting for and foreach confused. For and while loops do call any functions passed in as arguments on every iteration, foreach does not. Which is why its better to call functions such as strlen()
and count()
, just to give a couple of examples, outside of a for or while loop. The overhead we were experiencing was not from foreach but from array_keys()
. When array_keys()
is called it must generate a new array, which is why it is almost twice as slow. So it is best to drop the array_keys()
function all-together and just iterate over the array and retrieve the key value pair. Sorry for any confusion this may have caused.
Sources:
!!END OF UPDATE!!
To the best of my knowledge there is no security risk with any of those implementations. You are iterating a construct that already exists. Any security issues would have happened before this point. Except of course if you are using user supplied data, such as GET and POST. These you should sanitize and validate before using, which is something you could do with one of those foreach loops. Or you could also check out filter_input_array()
and its cousins.
I know I personally would not use the second implementation due to the lack of legibility. At least with the first and third implementations you can visually see that a value is being changed. The second is not readily obvious. However, it is most likely the more efficient. I have used both the first and third myself, but more often use the third. Think it has to do with what mood I'm in. Hope this helps, I'm interested to hear what others might have to say :)