There are lots of “Why does PHP throw an error here?” questions. Well, this is a little different. I found the following code while reworking some code written by a coworker:
foreach($arr as $key => $value) {http://google.com/
echo $value;
// ...
}
My first thought: “Umm…how embarrassing; he must have accidentally pasted that in there…” followed by: “Wait…there’s no way this code actually runs…that should be a syntax error”. And yet:
$ php -l test.php
No syntax errors detected
And indeed, (like so much PHP code that seemingly shouldn’t run) it runs in production without trouble. So I did a little testing:
foreach($arr as $key => $value) {http://google.com/ <-- original, no error
foreach($arr as $key => $value) {http: <-- also no syntax error
foreach($arr as $key => $value) {http <-- bingo! "Unexpected T_ECHO..."
What little tidbit of PHP’s grammar is producing such strange results?
(I am using PHP 5.3.5)
The
http:is being interpreted as a label (which are used forgotostatements), and the//google.com/as a comment (which can easily be seen through syntax highlighting).Documentation on goto: