2

我正在尝试使用 ("||") 运算符构建 PHPif语句or,但它似乎不起作用。

   $country_code = "example_country_code";

   if ($country_code != 'example_country_code' || !clientIscrawler()) {
       echo 'the script can be executed';
   }
   else {
       echo 'skipping';
   }

对于给定的示例,它应该被回显跳过,但它不会那样发生。我究竟做错了什么?

4

5 回答 5

2

也许双重否定会给你带来问题。让我们将其重写为:

!($country_code == 'example_country_code') || !clientIscrawler()

这可以转化为等价条件&&

!($country_code == 'example_country_code' && clientIscrawler())

通过反转if你会得到这个:

if ($country_code == 'example_country_code' && clientIscrawler()) {
    echo 'skipping';
} else {
    echo 'the script can be executed';
}

因此,在您的代码中,只有在真实情况下才会打印跳过clientIscrawler()

于 2012-11-15T14:30:19.853 回答
2

如果 OR 运算符有多个条件,在这种情况下,您不希望if语句评估为 true,则语法为:

if(!($something == "something" || $something == 'somethingelse')){
    do stuff...
}

这是一个例子:

$apples = array (
 1 => "Pink Lady",
 2 => "Granny Smith",
 3 => "Macintosh",
 4 => "Breaburn"
);

foreach($apples as $apple){

    // You don't want to echo out if the apple name is "Pink Lady" or "Macintosh"

    if(!($apple == "Pink Lady" || $apple == "Macintosh")){

        echo $apple."<br />";

    }
}

// Output is:
Granny Smith
Breaburn
于 2015-03-09T14:37:45.397 回答
0

在您给定的代码中,这完全取决于您的函数调用

 !clientIscrawler()

script can be executed只有当您的函数调用返回时,您才会获得输出FALSE。我认为它TRUE现在正在返回,这就是您没有获得所需输出的原因。

于 2012-11-15T14:25:14.237 回答
-2

也许这可以帮助你:

if ( ($country_code != 'example_country_code') || clientIscrawler() == false) {
于 2012-11-15T14:30:28.263 回答
-3

试试这个方法:

if ( ($country_code != 'example_country_code') || !clientIscrawler()) { ...
于 2012-11-15T14:18:19.663 回答