3

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';        
    }

}
8
  • What exactly do you want? Commented Jul 31, 2014 at 12:11
  • Wants to know why the result comes out EqualEqual, there's only one array element with the key "X" so, it should be Equal. Commented Jul 31, 2014 at 12:12
  • 1
    why not in_array() same keys and values Commented Jul 31, 2014 at 12:14
  • It's printing out Equal for "X" == "0" as well as for "X" == "X" - FYI Commented Jul 31, 2014 at 12:15
  • php.net/manual/en/language.operators.comparison.php Commented Jul 31, 2014 at 12:15

2 Answers 2

6

Use:

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

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

Sign up to request clarification or add additional context in comments.

9 Comments

Why downvote? My answer does as the OP wants and is functional.
it's the answer, but explain why it's the answer. ( I didn't downvote)
Sometimes type juggling is really counter-intuitive
For clarification the == is a loose comparison syntax, it it will cast the variable to multiple types "type juggling" so if your comparing (int) 1 to (string) 1 you will get a true return. Using the === operator will not type juggle but will return an exact match. Comparing (int) 1 to (string) 1 will return false
So using === when comparing strings is recommended. Highly
|
1
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 "==".

2 Comments

Yes, but "===" not working if $var come from a $_GET variable
if form get, the same is happening?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.