Unexpected T_ELSE error in PHP

I am working on an example from a php book and 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;


?>
+3
source share
4 answers

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 semicolon at the end of your if statements. This means that the subsequent opening bracket was a local block that always executes. This caused a problem because later you had an operator elsethat was not bound to the operator if; and

  • Execution is "$agent"not necessary and is not recommended. Just go to $agent.

+6
source

At the end of the instructions ifthere ;.

The reason for the error:

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

, if , .

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

Unexpected else, if, , , blk A, . , else, , if, . , statement (s):

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

remove the half-columns from the end of the lines with "if" in them.

+3
source

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

+1
source

Source: https://habr.com/ru/post/1741202/


All Articles