Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php string comparasion to 0 integer returns true? [duplicate]

Tags:

php

Possible Duplicate:
Why does PHP consider 0 to be equal to a string?

I have this piece of code:

$o['group'] = "prueba";
if( $o['group'] == 0){
    die("test");
}

Why it print test? how can be possible that a string is equal to zero?

like image 964
Arnold Roa Avatar asked Dec 29 '11 18:12

Arnold Roa


People also ask

Why would you use === instead of == in PHP?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

Can we compare string and integer PHP?

Check the second table, where it says that comparing the integer 0 to a string "php" using == shall be true. What happens is that the string is converted to integer, and non-numeric strings (strings that do not contain or begin with a number) convert to 0 .

Can you use == to compare strings in PHP?

The assignment operator assigns the variable on the left to have a new value as the variable on right, while the equal operator == tests for equality and returns true or false as per the comparison results. Example: This example describes the string comparison using the == operator.

Is 0 an integer in PHP?

PHP converts the string to an int, which is 0 (as it doesn't contain any number representation).


2 Answers

if you want it to exactly match the string try using the exact typof three equal signs like so
if( $o['group'] === 0){
the == will always evaluate to true when comparing a string to a integer of 0

'a string' == 0 also evaluates to true because any string is converted into an integer when compared with an integer. If PHP can't properly convert the string then it is evaluated as 0. So 0 is equal to 0, which equates as true.

From here

like image 70
Laurence Burke Avatar answered Oct 19 '22 05:10

Laurence Burke


Use comparison operator with type check "===". Look here for the example http://php.net/manual/en/language.operators.comparison.php and explanation why non-numerical string compared to zero always returns true.

like image 10
Alex Z Avatar answered Oct 19 '22 07:10

Alex Z