在 if else PHP 语句中使用 AND/OR

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4405795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:57:46  来源:igfitidea点击:

Using AND/OR in if else PHP statement

phpif-statement

提问by methuselah

How do you use 'AND/OR' in an if else PHP statement? Would it be:

你如何在 if else PHP 语句中使用“AND/OR”?可不可能是:

1) AND

1) 和

if ($status = 'clear' AND $pRent == 0) {
    mysql_query("UPDATE rent 
                    SET dNo = '$id', 
                        status = 'clear', 
                        colour = '#3C0' 
                  WHERE rent.id = $id");
} 

2) OR

2) 或

if ($status = 'clear' OR $pRent == 0) {
    mysql_query("UPDATE rent 
                    SET dNo = '$id', 
                        status = 'clear', 
                        colour = '#3C0' 
                  WHERE rent.id = $id");
} 

回答by deceze

Yes. The answer is yes.
http://www.php.net/manual/en/language.operators.logical.php

是的。答案是肯定的。
http://www.php.net/manual/en/language.operators.logical.php



Two things though:

不过有两点:

  • Many programmers prefer &&and ||instead of andand or, but they work the same (safe for precedence).
  • $status = 'clear'should probably be $status == 'clear'. =is assignment, ==is comparison.
  • 许多程序员更喜欢&&and||而不是andand or,但它们的工作方式相同(安全优先)。
  • $status = 'clear'应该是$status == 'clear'=是赋值,==是比较。

回答by Tanker

A bit late but don't matter...
the question is "How do you use...?" short answer is you are doing it correct

有点晚了但没关系……
问题是“你如何使用……?” 简短的回答是你做对了



另一个问题是“你什么时候使用它?”


我使用&&&&代替ANDAND||||代替OROR

$a = 1
$b = 3

Now,

现在,

if ($a == 1 && $b == 1) { TRUE } else { FALSE }

in this case the result is "FALSE" because B is not 1, now what if

在这种情况下,结果是“FALSE”,因为 B 不是 1,现在如果

if ($a == 1 || $b == 1) { TRUE } else { FALSE }

This will return "TRUE" even if B still not the value we asking for, there is another way to return TRUE without the use of OR / || and that would be XOR

即使 B 仍然不是我们要求的值,这也会返回“TRUE”,还有另一种方法可以在不使用 OR / || 的情况下返回 TRUE 那将是异或

if ($a == 1 xor $b == 1) { TRUE } else { FALSE }

in this case we need only one of our variables to be true BUT NOT BOTH if both are TRUE the result would be FALSE.

在这种情况下,我们只需要我们的变量之一为真,但不是两个都为真,则结果将为假。

I hope this helps...

我希望这有帮助...

more in:
http://www.php.net/manual/en/language.operators.logical.php

更多信息:http:
//www.php.net/manual/en/language.operators.logical.php

回答by redreinard

There's some joking, and misleading comments, even partially incorrect information in the answers here. I'd like to try to improve on them:

这里的答案中有一些开玩笑和误导性评论,甚至是部分不正确的信息。我想尝试改进它们:

First, as some have pointed out, you have a bug in your code that relates to the question:

首先,正如一些人指出的那样,您的代码中有一个与问题相关的错误:

if ($status = 'clear' AND $pRent == 0)

should be (note the ==instead of =in the first part):

应该是(注意==而不是=在第一部分):

if ($status == 'clear' AND $pRent == 0)

which in this caseis functionally equivalent to

在这种情况下,它功能上等同于

if ($status == 'clear' && $pRent == 0)

Second, note that these operators (and or && ||) are short-circuit operators. That means if the answer can be determined with certainty from the first expression, the second one is never evaluated. Again this doesn't matter for your debugged line above, but it is extremely important when you are combining these operators with assignments, because

其次,请注意这些运算符 ( and or && ||) 是短路运算符。这意味着如果可以从第一个表达式确定地确定答案,则永远不会评估第二个表达式。同样,这对于上面的调试行无关紧要,但是当您将这些运算符与赋值组合时,这一点非常重要,因为

Third, the real difference between and orand && ||is their operator precedence. Specifically the importance is that && ||have higher precedence than the assignment operators (= += -= *= **= /= .= %= &= |= ^= <<= >>=) while and orhave lower precendence than the assignment operators. Thus in a statement that combines the use of assignment and logical evaluation it matters which one you choose.

第三and or和之间的真正区别在于&& ||它们的运算符优先级。具体来说,重要的是&& ||优先级高于赋值运算符 ( = += -= *= **= /= .= %= &= |= ^= <<= >>=) 而and or优先级低于赋值运算符。因此,在结合使用赋值和逻辑评估的语句中,您选择哪一个很重要。

Modified examples from PHP's page on logical operators:

PHP 页面上关于逻辑运算符的修改示例:

$e = false || true;

will evaluate to trueand assign that value to $e, because ||has higher operator precedence than =, and therefore it essentially evaluates like this:

将计算为true并将该值分配给$e,因为||运算符优先级高于=,因此它的计算本质上是这样的:

$e = (false || true);

however

然而

$e = false or true;

will assign falseto $e(and then perform the oroperation and evaluate true) because =has higher operator precedence than or, essentially evaluating like this:

将分配false$e(然后执行or操作和评估true),因为=具有比 更高的运算符优先级or,本质上是这样评估的:

($e = false) or true;

The fact that this ambiguity even exists makes a lot of programmers just always use && ||and then everything works clearly as one would expect in a language like C, ie. logical operations first, then assignment.

这种歧义甚至存在的事实让很多程序员总是使用&& ||,然后一切都像人们期望的那样在像 C 这样的语言中清晰地工作,即。先逻辑运算,再赋值。

Some languages like Perl use this kind of construct frequently in a format similar to this:

一些语言(如 Perl)经常以类似于以下的格式使用这种结构:

$connection = database_connect($parameters) or die("Unable to connect to DB.");

This would theoretically assign the database connection to $connection, or if that failed (and we're assuming here the function would return something that evalues to falsein that case), it will end the script with an error message. Because of short-circuiting, if the database connection succeeds, the die()is never evaluated.

这理论上会将数据库连接分配给$connection,或者如果失败(我们在这里假设该函数将返回false在这种情况下评估为的内容),它将以错误消息结束脚本。由于短路,如果数据库连接成功,die()则永远不会评估 。

Some languages that allow for this construct straight out forbid assignments in conditional/logical statements (like Python) to remove the amiguity the other way round.

一些允许这种构造的语言禁止在条件/逻辑语句(如 Python)中进行赋值,以反过来消除歧义。

PHP went with allowing both, so you just have to learn about your two options once and then code how you'd like, but hopefully you'll be consistent one way or another.

PHP 允许同时使用这两个选项,因此您只需要了解一次您的两个选项,然后按照您喜欢的方式编写代码,但希望您能以一种或另一种方式保持一致。

Whenever in doubt, just throw in an extra set of parenthesis, which removes all ambiguity. These will always be the same:

如有疑问,只需添加一组额外的括号,即可消除所有歧义。这些将始终相同:

$e = (false || true);
$e = (false or true);

Armed with all that knowledge, I prefer using and orbecause I feel that it makes the code more readable. I just have a rule not to combine assignments with logical evaluations. But at that point it's just a preference, and consistency matters a lot more here than which side you choose.

有了所有这些知识,我更喜欢使用,and or因为我觉得它使代码更具可读性。我只是有一条规则,不要将作业与逻辑评估结合起来。但在这一点上,这只是一种偏好,一致性在这里比你选择哪一边更重要。

回答by Asaph

You have 2 issues here.

你在这里有两个问题。

  1. use ==for comparison. You've used =which is for assignment.

  2. use &&for "and" and ||for "or". andand orwill work but they are unconventional.

  1. 使用==进行比较。您已经使用=which 用于分配。

  2. 使用&&了“与”和||为“或”。and并且or会起作用,但它们是非常规的。

回答by Dan D.

AND is &&and OR is ||like in C.

AND&&和 OR||就像在 C 中一样。

回答by alex

ANDand ORare just syntactic sugar for &&and ||, like in JavaScript, or other C styled syntax languages.

ANDOR只是语法糖&&||,像JavaScript或其他C风格的语法语言。

It appears ANDand ORhave lower precedencethan their C style equivalents.

出现AND并且OR具有比它们的 C 风格等价物低的优先级

回答by pooja

for AND you use

为您使用

if ($status = 'clear' && $pRent == 0) {
    mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
} 

for OR you use

为 OR 您使用

if ($status = 'clear' || $pRent == 0) {
    mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
} 

回答by Anush Prem

i think i am having a bit of confusion here. :) But seems no one else have ..

我想我在这里有点困惑。:) 但似乎没有其他人有..

Are you asking which one to use in this scenario? If Yes then And is the correct answer.

你问在这个场景中使用哪个?如果是,则And 是正确答案

If you are asking about how the operators are working, then

如果您询问操作员的工作方式,那么

In php both AND, &&and OR, ||will work in the same way. If you are new in programming and php is one of your first languages them i suggest using AND and OR, because it increases readability and reduces confusion when you check back. But if you are familiar with any other languages already then you might already have familiarized the && and || operators.

在 php 中,AND、&&OR、|| 将以同样的方式工作。如果您是编程新手并且 php 是您的首选语言之一,我建议您使用 AND 和 OR,因为它可以提高可读性并减少您在查看时的混淆。但是如果您已经熟悉任何其他语言,那么您可能已经熟悉 && 和 || 运营商。

回答by PureLocal Business Directory

<?php
$val1 = rand(1,4); 
$val2=rand(1,4); 

if ($pars[$last0] == "reviews" && $pars[$last] > 0) { 
    echo widget("Bootstrap Theme - Member Profile - Read Review",'',$w[website_id],$w);
} else { ?>
    <div class="w100">
        <div style="background:transparent!important;" class="w100 well" id="postreview">
            <?php 
            $_GET[user_id] = $user[user_id];
            $_GET[member_id] = $_COOKIE[userid];
            $_GET[subaction] = "savereview"; 
            $_GET[ip] = $_SERVER[REMOTE_ADDR]; 
            $_GET[httpr] = $_ENV[requesturl]; 
            echo form("member_review","",$w[website_id],$w);?>
        </div></div>

ive replaced the 'else' with '&&' so both are placed ... argh

我用'&&'替换了'else',所以两者都被放置...... argh

回答by jofo

"AND" does not work in my PHP code.

“AND”在我的 PHP 代码中不起作用。

Server's version maybe?

服务器的版本可以吗?

"&&" works fine.

“&&“ 工作正常。