Elitmiar
Elitmiar

Reputation: 36839

if statement issue

I have a variable called root. The value for this variable is 0

$root = 0;

if($root == "readmore"){

            $root = 1701;
        }

somehow for some weird reason if $root is 0 it still enteres the if statement above? I have no idea what it could be

Upvotes: 1

Views: 94

Answers (3)

Pascal MARTIN
Pascal MARTIN

Reputation: 401002

basically, you are doing this comparison :

if (0 == 'readmore') {
  // ...
}

Which means 'readmore' will be converted to an integer ; and 'readmore', converted to an integer, is 0.

See Type Juggling in the manual, about that, and also String conversion to numbers, which states (quoting) :

If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).


You might want to use the === operator, which will prevent that kind of conversion :

if($root === "readmore") {
  // You will not enter here, if $root is 0
}

See Comparison Operators.

Upvotes: 3

Blair McMillan
Blair McMillan

Reputation: 5349

Try

$root = 0;

if($root === "readmore"){

        $root = 1701;
    }

To check the type as well.

Upvotes: 2

Ben James
Ben James

Reputation: 125167

This is because, with type-juggling, 0 is considered equal to "readmore". You are asking PHP to compare a string to an integer, and it will interpret any string that doesn't contain digits as a 0.

If you use if ($root === "readmore") ..., PHP will check the type as well as the value of the variable.

Upvotes: 3

Related Questions