0

I am getting wrong output from this if else syntax, what could be wrong here? The output should be wrong answer, but i am getting the right answer output.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
    <?php

    $math = 22+22+22;

    if($math = 22222222) {
        echo "Right answer";
    }
    else
    {
        echo "Wrong answer";
    }

    ?>
    </body>
</html>
  • Assignment in a conditional, as you have accidentally done here, may not always evaluate to true, although it does in your case because of the value you're using. An assignment expression like `$math = 22222222` evaluates to the assigned value, but if you assign a falsey value (`0`, `[]`, `''`, etc.) the conditional will evaluate to false. – Don't Panic Jan 16 '18 at 23:35

1 Answers1

5

You need to change = to ===.

if($math === 22222222) {

= is used to assign a value to a variable

== is used for loose comparison

=== is used for strict comparison

This answer right here as pointed by Gildas gives a good explanation of how == is different from ===

Spoody
  • 2,852
  • 1
  • 26
  • 36
  • 1
    Allow me to augment your answer with this thread: https://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp. Personnaly, I solely use similarity comparison. – Gildas Jan 16 '18 at 23:36
  • @Gildas Sure, I'll add the explanation to my answer. – Spoody Jan 16 '18 at 23:37