tags:

views:

67

answers:

2

Whey does this evaluate to true?

<?php


$val2=0;

//outputs that is an error123
if($val2=='error123'){
   echo 'that is an error123<br />';
}else{
   echo 'that is not an error123<br />';
}  
+9  A: 

You're comparing a string to an integer. To make the comparison the string is first converted to an integer. When 'error123' is converted to an integer it becomes 0.

echo intval("error123");

Result:

0

In the PHP manual there is an explanation for this behaviour.

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

There is a quick reference page PHP type comparison tables that shows you the result of various comparions. See the table "Loose comparisons with ==". The interesting part with regard to this question is that 0 == "php" is shown as TRUE.

There is also a page on type juggling. A user comment on that page gives nearly the exact same example as this.

If you don't want the type juggling use === instead of ==.

Mark Byers
True. And insane.
eyelidlessness
So if he were to go the other way around, `'error123'==$val2`, would this evaluate to false?
Wallacoloo
@wallacoloo No, it would also evaluate as true. The operator == forces a numerical evaluation, if one of the operands is a number... and also if the strings are "numeric". It's insane, indeed. http://www.php.net/manual/en/language.operators.comparison.php
leonbloy
i guess makes sense; don't use ===. or int's are dominant
timpone
+2  A: 

Give this a try: $val2==='error123'

That will evaluate the value and the type of the variable. More here:

http://us.php.net/manual/en/language.operators.comparison.php

uotonyh