mercredi 15 janvier 2020

Why is my if statement entered even though its condition seems false? [closed]

I am writting a script in PHP, and I have a switch case in which there is an if statement in every case. Each if statement's condition is two ints (or so I think, I used the is_int function on my variable to check) being compared with a ">" operator. However, even when the comparison seems clearly false, the script enters and executes the code in the if statement.

echo nl2br("Diff date converted to int:".$diff_date_int."\n\n");
switch ($message_period) {

            case '1':
                echo nl2br("Entered case 1\n\n");
                if ($diff_date_int>2635000) {                   

                    echo nl2br("Entered the if statement!!\n\n\n\n");

                }
                else{echo nl2br("\n\n\n\n");}
                break;

The output of this is:

Diff date converted to int:367

Entered case 1

Entered the if statement!!

Even though 367>2635000 is false, the code in the if statement is executed. I fixed this using a variable:

echo nl2br("Diff date converted to int:".$diff_date_int."\n\n");
switch ($message_period) {

            case '1':
                $variable = 2635000
                echo nl2br("Entered case 1\n\n");
                if ($diff_date_int>$variable) {                  

                    echo nl2br("Entered the if statement!!\n\n\n\n");

                }
                else{echo nl2br("\n\n\n\n");}
                break;

The output of this is:

Diff date converted to int:367

Entered case 1

Technically speaking, this seems to have fixed the problem, however I am very curious to know why PHP acts like this. Just to specify, the entire switch case has a total of 7 cases and a default, all seven similar to this one, just with a different number to compare my $diff_date_int variable to. (except case 0 and default, which both just has an echo in it)

Aucun commentaire:

Enregistrer un commentaire