Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is PHP not throwing a parse error?

Tags:

php

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)

like image 421
jches Avatar asked Jan 19 '12 23:01

jches


People also ask

How can solve parse error in PHP?

To solve the missing parenthesis error in PHP, the code has to be checked from the beginning to search for it. One way to avoid errors is to use proper indentation in the code. Once all the parentheses in the code have been set correctly, parse error: syntax error, unexpected $end will be fixed.

What is unexpected error in PHP?

A parse error: syntax error, unexpected appears when the PHP interpreter detects a missing element. Most of the time, it is caused by a missing curly bracket “}”. To solve this, it will require you to scan the entire file to find the source of the error.


1 Answers

The http: is being interpreted as a label (which are used for goto statements), and the //google.com/ as a comment (which can easily be seen through syntax highlighting).

Documentation on goto:

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label.

like image 154
Tim Cooper Avatar answered Oct 15 '22 14:10

Tim Cooper