Home  >  Article  >  Backend Development  >  Efficient usage of php logical operators && and ||

Efficient usage of php logical operators && and ||

WBOY
WBOYOriginal
2016-07-25 09:00:521403browse
There are two logical operators && and || in PHP. You know their efficient usage. If you don’t know, just read the introduction of this article. I believe you will gain something.

In php, logical operators are nothing more than performing logical operations on values. Are there other uses? Let’s take a look at the following code first. Giving conclusions in advance is (&&) or (||)" These two operators can speed up the running speed of PHP code in the program.

Code:

<?php
$test="李四";
$test=="张三"&&$test="张三来了";
echo $test;  //输出“李四”
$test="李四";
$test=="张三"||$test="张三不在这里";
echo $test;  //输出“张三不在这里”
?>

 Why does this result occur? If we follow the usual method, we must at least use an IF statement to judge. But now just two logical operations will change the value of the variable. Let's analyze how it works.

  In the expressions on both sides involved in logical operations, operations are performed from left to right. As long as one of the "AND" operations is false, the result of the entire expression is false. Therefore, when the expression on the left is false, no further calculation is needed. This kind of processing is undoubtedly of great benefit to the running efficiency of the program. So as the title says, it is an efficient usage. But logical OR is different: as long as one is true, the entire expression is true. Therefore, when the left side is false, the expression judgment on the right side must be run.

The above example can of course be realized through conditional judgment statements. In the current situation, one is to reduce the amount of code, and the most important thing is to increase the execution efficiency of the program. The key to grasping this is the direction in which the expression runs, which is from left to right. Operation stops when the first value determines the value of the entire expression. It is worth explaining that the right hand side can be an expression or a function, but it cannot be a series of statement combinations or output statements. After all, it is an integral part of a logical expression.

Summary: For the "and" (&&) operation: x && y When x is false, skip directly and y will not be executed; For the "or" (||) operation: x||y When x is true, skip directly and y will not be executed.

By the way, vice versa.

That’s it for today’s php tutorial, do you understand? Looking forward to your rapid progress.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn