Unexpected T_ELSE error in PHP [closed]
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 questionI 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:
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 anif
statement; andDoing
"$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"));
精彩评论