tags:

views:

44

answers:

3
+1  Q: 

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

+3  A: 

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.

Ben James
+2  A: 

Try

$root = 0;

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

        $root = 1701;
    }

To check the type as well.

Blair McMillan
+3  A: 

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.

Pascal MARTIN
+1 for being more thorough than me with useful links!
Ben James