July 16th, 2003
foreach
Since I started programming in PHP, I’ve always used while loops to process my arrays, as follows:
while (list($key, $value) = each ($arr)) {
echo "$key : $valuen”;
}
Seemed rather efficient and it made sense to me. I had seen a few people use foreach, but never really paid a lot of attention to it.
However, then I read in the comments in PHP’s online manual that foreach is about 30-40% faster than using while.
I’m not one to believe everything that I read, but foreach has other advantages also:
- It works on a copy of the array, so it doens’t modify the array pointer on each iteration (it does move the pointer to the end of the array after the foreach call has completed)
- It automatically starts at the beginning of the array, so you don’t have to do a reset() before foreach
It also seems a little easier to code once you get used to seeing it. Here is the foreach equivalent of the while command above:
foreach ($arr as $key => $value) {
echo "$key : $valuen”;
}
Note that you can leave out the $key part as follows:
foreach ($arr as $value) {
echo "Value: $valuen”;
}
So, use foreach when you want to process all the elements in an array — it’s faster and easier to use!
Filed under:
1 Comment