-2

I have started to learn some basic PHP. So far everything worked perfectly until I tried to run some IF/ELSE statements embedded into the markup as you can see in the snipet bellow:

<?php 
$msg = 0;
echo $msg;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
</head>
<body>
    <?php if ($msg = 5){ ?>
        <h1>5</h1>
    <?php } elseif ($msg = 0) { ?>
        <h1> 0 </h1>
    <?php } else { ?>
        <h1>Whatever</h1>
    <?php } ?>
</body>
</html> 

The result is always the first if statement, even if it doesn't meet the condition. In this case the result is:

0

5

Tried everything I knew and searched a lot without any results. What am I doing wrong here?

Jo.joe
  • 37
  • 2
  • 4
    YOU missed `=` in your if condition. it should be `==`. – Hamza Zafeer Nov 16 '18 at 13:28
  • Also, if you are interested to know if the type is correct, rather than just the value after type [juggling](http://php.net/manual/en/language.types.type-juggling.php), then use `===` – Klors Nov 16 '18 at 13:35

4 Answers4

1

This is a simple syntax error, it needs to be:

<?php 
$msg = 0;
echo $msg;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
</head>
<body>
    <?php if ($msg == 5){ ?>
        <h1>5</h1>
    <?php } elseif ($msg == 0) { ?>
        <h1> 0 </h1>
    <?php } else { ?>
        <h1>Whatever</h1>
    <?php } ?>
</body>
</html> 

Notice the == which compares things vs. = which sets things.

Adam
  • 1,149
  • 2
  • 14
  • 21
1

The = sign is for assignment; in order to do a comparison you need to use ==:

<?php if ($msg == 5){ ?>
Tordek
  • 10,628
  • 3
  • 36
  • 67
0

The problem is in the condition -> ($msg = 5) It should be == ($msg == 5) instead of ($msg = 5).

When you are comparing two values you need to use double equal sign not single. Single means you are assigning value to the variable.

Don'g give up!!

Good luck!

0

<?php 
$msg = 0;
echo $msg;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Test</title>
</head>
<body>
    <?php if ($msg == 5){ ?>
        <h1>5</h1>
    <?php } elseif ($msg == 0) { ?>
        <h1> 0 </h1>
    <?php } else { ?>
        <h1>Whatever</h1>
    <?php } ?>
</body>
</html> 
Rm khan
  • 9
  • 2