0

I have encountered a very weird and concerning problem in some of my PHP code. A variable that I have returns true in an IF statement when it clearly should return false.

$pr = $_SESSION['fin_print_printer']; //this should equal 0     
print $pr; //this returns 0, as it should
if($pr == "L"){
   print "local";
} else {
       print "serve";
} 
print $pr; //this returns 0 again, as it should

This prints "local" in my script (in between the two zeros) and does not print "serve". With over 100,000 lines of code in my project, I've not experienced this issue yet, and now I can't figure out what is going on.

If I do if($pr === "L"), then it works as expected, but the above does not.

3 Answers3

1

PHP is trying to typecast 'L' into an int, which results in 0.

intval('L'); // 0

Change your code into the following so it will take types into account:

if($pr === "L")
{
    print "local";
} 
else 
{
    print "serve";
} 

Or manually typecast $pr to a string.

// You can also to (string)$pr ("0" instead of 0)
if(strval($pr) == "L")
{
    print "local";
} 
else 
{
    print "serve";
} 
MisterBla
  • 2,355
  • 1
  • 18
  • 29
  • Thanks! As another user commented, it is logically impossible for L to equal 0, that's why I found this so mind-boggling. But thank you for the help. Using strval() works great (as with === as was expected). – Kyle Lawrence Aug 31 '13 at 20:49
  • @KyleLawrence You can also use `(string)$pr` to typecast it. Just as an additional note. About the L being 0, it's just the PHP Interpreter trying to compare L to an integer because `$pr` in an int. – MisterBla Aug 31 '13 at 20:56
0

Maybe if you use typecasting (I did't check it):

if ( (string)$pr == "L" ) {
   print "local";
} else {
       print "serve";
}
0

Little known approach: You can also do the casting like

if ("L" == $pr) {

Because with loose comparisons, PHP casts the right value to the left value's type, and as you've already been made aware, while string(1)"L" is casted to int(0), int(0) is casted to string(1)"0".

boen_robot
  • 1,450
  • 12
  • 24