Home  >  Article  >  Backend Development  >  code - Some questions about operators in php?

code - Some questions about operators in php?

WBOY
WBOYOriginal
2016-07-06 13:53:55984browse

In php (or in other languages?), similar to

<code>if(!$a=b){
    .....
}</code>

or

<code>empty($a)&&$a=array()</code>
What does

mean? What are the benefits of writing this way?

Reply content:

In php (or in other languages?), similar to

<code>if(!$a=b){
    .....
}</code>

or

<code>empty($a)&&$a=array()</code>
What does

mean? What are the benefits of writing this way?

Don’t write like this.
For example, I have been writing code for several years, and I don’t know the priority of ! and = at first glance

$a = someFunc();
if ($a) {
abc();
}

if ($a = someFunc()) {
abc();
}

if ( !($a = someFunc()) ) {
abc();
}

if ( ! $a = someFunc() ) {
abc();
}

($a = someFunc()) && abc();

Finally, use if else all the time. The code is fun for a while, but the maintenance is heartbreaking.

<code class="php">
empty($a) && $a=array()
//这是短路运算符,如同
if(empty($a)){
   $a=array();
}</code>

if(!$a=b){

<code>.....</code>

}
First assign value b
to $a and then!$a Just pay attention to the operator priority here

The expression before the second && is only to determine whether the variable is empty; the following expression is to determine whether it is an empty array, which can be omitted here

<code>    $a = FALSE; 
    $b = TRUE; 
    $c = 2;
    
    // $a为false,短路了,$c没有赋值20
    $a && $c=20;
    echo $c; // 2

    echo "<br />";

    // $b为true,走了下一步,$c被赋值20
    $b && $c=20;
    echo $c; // 20
</code>

Your code can be understood as: if $a does not exist, it is true, take the next step and assign a value to $a;

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