1

My question is why does..

$validationFail = "1";
$validationFail .= "i88"; 
$validationFail .= "w19"; 
echo $validationFail;
if($validationFail==1){
    echo "hello world";
}

output 1i88w19hello world

I know that the if fails with ===, but why does this happen?

(code ran in http://phpfiddle.org/ )

EnglishAdam
  • 1,380
  • 1
  • 19
  • 42
  • 1
    You're comparing a string to an integer. PHP has dynamic typing that prefers integer comparisons, in particular when both operands look like integers. – mario Jan 29 '15 at 01:36
  • so it converts the string to the first known integer? – EnglishAdam Jan 29 '15 at 01:37
  • Actually it would convert any string. Most strings would amount to zero in numeric context. Yours just happens to get cut down to a `1`. – mario Jan 29 '15 at 01:38
  • In php, compare string will use strcmp() instead of == , === will fail because of === will only return true when two variable contain exactly same value. – Deeper Jan 29 '15 at 01:38
  • Thank you both, apologies for the ignorance. But now i know! – EnglishAdam Jan 29 '15 at 01:39

1 Answers1

1

When you compare a string with a number, it converts the string to a number, and then compares that with the other number. Converting a string to a number works by reading the string until it gets to the first non-numeric character. So the string 1i88w19 becomes 1, and 1 == 1 is true.

Barmar
  • 741,623
  • 53
  • 500
  • 612