问题
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:
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
.
回答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