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.

4

3 回答 3

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";
} 
于 2013-08-31T01:16:50.963 回答
0

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

if ( (string)$pr == "L" ) {
   print "local";
} else {
       print "serve";
}
于 2013-08-31T01:05:23.633 回答
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".

于 2013-08-31T22:02:53.150 回答