user3895472
user3895472

Reputation: 41

php if inside foreach wrong

I have a problem with if inside foreach. The answer for code must be “Equal” but is “EqualEqual”.

Here is my code

$list=array(
    "X"     => "X",
    "0"     => "0",
    "2"     => "2",
    "3"     => "3"
);

$var="X";

foreach ($list as $key =>  $val){

    if ($var==$key) {
        echo 'Equal';        
    }

}

Upvotes: 3

Views: 107

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

var_dump('X' == 0);//true

reference - http://php.net/manual/en/language.operators.comparison.php

var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true

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. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

$a == $b    Equal   TRUE if $a is equal to $b after type juggling.
$a === $b   Identical   TRUE if $a is equal to $b, and they are of the same type.

so, try to use "===" instead of "==".

Upvotes: 1

t3chguy
t3chguy

Reputation: 1018

Use:

if ($var===$key) {
    echo 'Equal';        
}

You need === because var_dump($var==0); returns true, which is after type juggling.

Upvotes: 6

Related Questions