2012-03-23 132 views
1

我试图将一个已定义的代码与一组被阻止的国家/地区代码进行比较。在下面的例子中,国家代码被逮住我,如果块:为什么这个PHP比较失败?

$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>"; 
} 

我认为这对我的结果”

COUNTRY CODE: US 

我不希望‘US’被抓...我缺少什么

回答

10

你在做什么是OR -ing串在一起,因为转换为布尔值非空字符串是真实的,这个计算结果为以下几点:?

$country_code == true 

由于$country_code也是非空字符串,也计算为true

true == true 

因此,你TRUE

解决你的问题,你需要做什么佩卡提示:

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

参见:

+0

唉唉......太多的时间用Perl我猜。谢谢! – Paul 2012-03-23 17:32:18

5

我会做这个

$country_code = 'US'; 

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

您不能通过这种方式连接||并获得您期望的结果。它会一直返回TRUE,因为任何非空字符串的计算结果为true。由于对==左边的操作数相比,右侧的整个操作,你实际上是说:

if ($country_code == (TRUE ||TRUE||TRUE||TRUE||TRUE...); 

虽然这将是有效的做类似下面,失控:

if ($country_code == "N" || $country_code == "RO" || $country_code == "VN" ...) 

取而代之,使用in_array();

$countries = array("NG","RO","VN","GH",...); 
if (in_array($country_code, $countries) { 
    print "COUNTRY CODE: $country_code<br>"; 
} 
3

此:

("NG" || "RO" || "VN" || "GH" || "SN" || "TN" || "IN" || "ID" || "KE" || "CN" || "CI" || "ZA" || "DZ" || "RU") 

实际上是一个布尔值测试,说: “如果这些评估为true,那么真正的”。由于非空字符串是真的,所以这是真的。同样,“美国”将被视为真实。因此简化了我们得到的陈述: if(true == true)。

尝试使用数组和in_array函数。

+0

+1 in_array函数,这是一个更好的测试,然后我使用的ORs乐队。 – 2012-03-23 17:35:43

0

如果以这种方式完成,这将会简单得多。

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

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

这里你设置$country_code

if ($country_code == ("NG" || "RO" || "VN" || "GH" || "SN" || "TN" || "IN" || "ID" || "KE" || "CN" || "CI" || "ZA" || "DZ" || "RU")) { 

这里您评估$country_code针对真的没什么,但因为它的所有非空字符串,他们以评估TRUE,因为$country_code是一个非空字符串,它也计算为TRUE

print "COUNTRY CODE: $country_code<br>"; 

在这里您的打印$country_code,您在您的第一行中设置。

} 

你想要的是像这样

if (
    $country_code == "NG" || 
    $country_code == "RO" || 
    $country_code == "VN" || 
    $country_code == "GH" || 
    $country_code == "SN" || 
    $country_code == "TN" || 
    $country_code == "IN" || 
    $country_code == "ID" || 
    $country_code == "KE" || 
    $country_code == "CN" || 
    $country_code == "CI" || 
    $country_code == "ZA" || 
    $country_code == "DZ" || 
    $country_code == "RU" 
) {