为什么这个PHP比较失败了?

Pau*_*aul 1 php

我正在尝试将已定义的代码与一组被阻止的国家/地区代码进行比较.在以下示例中,国家/地区代码被我的if块捕获:

$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>";
}
Run Code Online (Sandbox Code Playgroud)

我看到这个结果"

COUNTRY CODE: US
Run Code Online (Sandbox Code Playgroud)

我不希望"美国"被抓住......我错过了什么?

Bra*_*rad 10

你在做什么是把OR字符串放在一起.由于转换为布尔值的非空字符串为true,因此计算结果如下:

$country_code == true
Run Code Online (Sandbox Code Playgroud)

由于$country_code也是一个非空字符串,它还评估为true:

true == true
Run Code Online (Sandbox Code Playgroud)

因此,你得到TRUE.

要解决您的问题,您需要做Pekka建议的事情:

if (in_array($country_code, array('NG', 'RO', etc.)))
Run Code Online (Sandbox Code Playgroud)

也可以看看:


Mic*_*ski 6

你不能||以这种方式连在一起,得到你期望的结果.它将返回TRUE,因为任何非空字符串的计算结果为true.由于左侧的==操作数与右侧的整个操作数进行比较,您实际上是这样说的:

if ($country_code == (TRUE ||TRUE||TRUE||TRUE||TRUE...);
Run Code Online (Sandbox Code Playgroud)

虽然做以下事情是有效的,但它失控了:

if ($country_code == "N" || $country_code == "RO" || $country_code == "VN" ...)
Run Code Online (Sandbox Code Playgroud)

相反,使用in_array();

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


mik*_*ing 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>";
}
Run Code Online (Sandbox Code Playgroud)