March 23, 2012

Why is this PHP comparison failing?

Question by Paul

I’m trying to compare a defined code against a set of blocked country codes. In the following example the country code is getting caught in my if block:

$country_code = 'US';

if ($country_code == ("NG" || "RO" || "VN" || "GH" || "SN" || "TN" || "IN" || "ID" || "KE" || "CN" || "CI" || "ZA" || "DZ" || "RU")) {
    print "COUNTRY CODE: $country_code<br>";
}

I see this for my results”

COUNTRY CODE: US

I wouldn’t expect ‘US’ to get caught…what am I missing?

Answer by Brad

What you are doing is OR-ing strings together. Since non-empty strings converted to boolean values are true, this evaluates to the following:

$country_code == true

Since $country_code is also a non-empty string, that also evaluates to true:

true == true

Thus, you get TRUE.

To solve your problem, you need to do what Pekka suggests:

if (in_array($country_code, array('NG', 'RO', etc.)))

See also:

Answer by Starx

This would be a lot simpler if done this way.

$codes = array("NG", "RO", "VN");

$search = array_search("NG");
if($search) {
    echo $codes[$search];
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!