Unexpected T_ELSE error in PHP [closed]

本秂侑毒 提交于 2019-12-05 02:58:07

问题


I am working on an example from a php book and am getting an error on line 8 with this code

<?php

$agent = getenv("HTTP_USER_AGENT");
if (preg_match("/MSIE/i", "$agent"));
{
    $result = "You are using Microsoft Internet Explorer";
}
else if (preg_match("/Mozilla/i", "$agent")); 
{
    $result = "You are using Mozilla firefox";
}
else {$result = "you are using $agent"; }

echo $result;


?>

回答1:


Try:

$agent = getenv("HTTP_USER_AGENT");
if (preg_match("/MSIE/i", $agent)) {
  $result = "You are using Microsoft Internet Explorer";
} else if (preg_match("/Mozilla/i", $agent)) {
  $result = "You are using Mozilla firefox";
} else {
  $result = "you are using $agent";
}

echo $result;

Two things:

  1. You had a semi-colon at the end of your if clauses. That means the subsequent opening brace was a local block that is always executed. That caused a problem because later you had an else statement that wasn't attached to an if statement; and

  2. Doing "$agent" is unnecessary and not recommended. Simply pass in $agent.




回答2:


There are ; at the end of if statements.

Cause of error:

if(...) ;
{
...
}

Will not cause any syntax error as the body of if is empty and the following block always gets executed. But

if(...) ;
{
  // blk A
} else {
...
}

will cause Unexpected else syntax error because the if as before has empty body and is followed by another block blk A which is not if's body. Now when an else if found after the block it cannot be matched with any if causing this error. The same would happen if we'd statement(s) in place of a block:

if(...) ;
 do_something;
else {
...
}



回答3:


remove the semi-colons from the end of the lines with "if" in them.




回答4:


Why do you have a semicolon here? if (preg_match("/MSIE/i", "$agent")); and here else if (preg_match("/Mozilla/i", "$agent"));



来源:https://stackoverflow.com/questions/2642512/unexpected-t-else-error-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!