开发者

Unexpected T_ELSE error in PHP [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.

This question was caused by a typo or a pro开发者_Python百科blem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

Closed 8 years ago.

Improve this question

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;


?>


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 {
...
}


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜