String is being shown as equal to a number

2019-08-06 09:54发布

问题:

I'm having a strange problem in some of my php. What seems to be happening is that 0 is being shown as equal to the string "done". Here's what's happening:

if(!isset($pointer)){
    $pointer = 0;   
}
error_log($pointer); //in this instance, I haven't set a pointer, returns 0
if($pointer == "done"){
    die();
}

For some reason, the second if statement is triggering and killing the script. I can't figure out why, when $pointer is equal to 0, it is apparently also equal to "done". Is this something super easy that I'm just overlooking?

I've worked around the situation, using === on the second if statement gives me the desired result, I would just like to understand why it wasn't working in the first place. Thank you for your time.

回答1:

It's a type comparison issue; as you say, using:

if($pointer === "done"){

forces a check against both value and type.

What is happening is that 'done' is being converted into a number for the comparison. Since there are no numbers in there, it's coming out as null. And null evaluates to 0 in your comparison.