You must be surprised/scared after reading title of this article. But I would say yes, foreach loop can create very confusing bug in your program/application if it has not been used in proper way. I will demonstrate the same in this article.
P.S.: This article does to mean to say foreach loop always creates problem, but it would create problem if not used in proper manner.
Let’s move to practical stuff to see this problem in action, please have a look at below code block:
Above code will give you following output.
Upto now foreach seems fine and nothing unusual happens. But now let’s see some unusal things with foreach now, writing same code again with just (very)minor change in it.
You must have guessed that it will give you same output but infact it is not true. It will give you following output.
Now you must be surprised and having question of WHY that happens. Let’s go through each step of above code which shows the real case.
Here array is declared and echoed by imploding array elements. So here nothing changed to array.
Here we have foreach loop, you must have noted & in front of $value, which means we are passing each element of $arr with reference instead of just value. So for each iteration we are assigning reference to array element. Once this iteration is completed $value will have reference to last element of $arr which is $arr and value is 3.
When this foreach starts $value holds 3 which is reference to $arr. This loop will create a confusing issue specially when accessing $value by value instead of reference. We will go through step of step each iteration.
Now you should have clear idea on why does that wierd thing happen with foreach loop. This bug was already reported back in 2004 (https://bugs.php.net/bug.php?id=29992), but this has not been considered as BUG.
So what can be the resolution for this issue? Its very simple, just remove reference which is assigned to $value, just have a look at below code block.
So this was the weird stuff I have found with foreach loop in PHP. Look forward to your comments on this.
Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.
View all posts by: Avinash