views:

172

answers:

4

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  A: 

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

brianreavis
+11  A: 

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 {
...
}
codaddict
Excellent and thorough analysis!
timdev
+3  A: 

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

timdev
+5  A: 

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.

cletus
brilliant, thanks for the explanation!
Jacksta