PHP中类似$a && $b = $c 语法的用法和实例

$a && $b = $c 表示:如果$a为真,则执行$b = $c,否则不执行。

可以用if语句替代:

if ($a) {
    $b = $c;
}

其他php7写法:

$a = 1;$b = 2;$c = 3;
$a? :$b=$c;
echo "a:$a";
echo "b:$b";
echo "c:$c";
//输出是
a:1b:2c:3
$a = 0;$b = 2;$c = 3;
$a? :$b=$c;
echo "a:$a";
echo "b:$b";
echo "c:$c";
//输出是
a:0b:3c:3

如果$a 为真则执行$b 否则不执行

return $a && $b;

如果$a 为真则执行$a=$b 否则不执行

$a && $a=$b;

 注意:这是种写法,但在项目里一般是不允许这样写,一是这种语法那天不支持了,二是给别人造成阅读上的障碍,代码风格难以统一

 

实例1:

$a = 1;$b = 2;$c = 3;
$a && $b = $c;
echo "a:$a";
echo "b:$b";
echo "c:$c";
//输出是
a:1 b:3 c:3

实例2:

$a = 0;$b = 2;$c = 3;
$a && $b = $c;
echo "a:$a";
echo "b:$b";
echo "c:$c";
//输出是
a:0 b:2 c:3

实例3:

$a = 1;$b = 0;$c = 3;
$a && $b = $c;
echo "a:$a";
echo "b:$b";
echo "c:$c";
//输出是
a:1 b:3 c:3

实例4:

$a = 1;$b = 2;$c = 3;
$a ||$b = $c;
echo "a:$a";
echo "b:$b";
echo "c:$c";
//输出是
a:1 b:2 c:3

实例5:

$a = 0;$b = 2;$c = 3;
$a || $b = $c;
echo "a:$a";
echo "b:$b";
echo "c:$c";
//输出是
a:0 b:3 c:3

实例6:

$a = 1;$b = 2;$c = 3;$d = 4;$e = ['10'];
$a && $b && $c != $d && $e[] = $c;
print_r(['$a'=>$a,'$b'=>$b,'$c'=>$c,'$d'=>$d,'$e'=>$e]);
//输出是
Array
(
    [$a] => 1
    [$b] => 2
    [$c] => 3
    [$d] => 4
    [$e] => Array
        (
            [0] => 10
            [1] => 3
        )

)

实例7:

$a = 1;$b = 0;$c = 3;$d = 4;$e = ['10'];
$a && $b && $c != $d && $e[] = $c;
print_r(['$a'=>$a,'$b'=>$b,'$c'=>$c,'$d'=>$d,'$e'=>$e]);
输出是
Array
(
    [$a] => 1
    [$b] => 0
    [$c] => 3
    [$d] => 4
    [$e] => Array
        (
            [0] => 10
        )

)

实例8:

$a = 0;$b = 2;$c = 3;$d = 4;$e = ['10'];
$a && $b && $c != $d && $e[] = $c;
print_r(['$a'=>$a,'$b'=>$b,'$c'=>$c,'$d'=>$d,'$e'=>$e]);
//输出是
Array
(
    [$a] => 0
    [$b] => 2
    [$c] => 3
    [$d] => 4
    [$e] => Array
        (
            [0] => 10
        )

)

实例9:

$a = 1;$b = 2;$c = 3;$d = 4;$e = ['10'];
$a && $b && $c != $d && $e[] = $c;
print_r(['$a'=>$a,'$b'=>$b,'$c'=>$c,'$d'=>$d,'$e'=>$e]);
//输出是
Array
(
    [$a] => 1
    [$b] => 2
    [$c] => 3
    [$d] => 4
    [$e] => Array
        (
            [0] => 10
            [1] => 3
        )

)

实例10:

$a = 1;$b = 2;$c = 3;$d = 3;$e = ['10'];
$a && $b && $c != $d && $e[] = $c;
print_r(['$a'=>$a,'$b'=>$b,'$c'=>$c,'$d'=>$d,'$e'=>$e]);
//输出是
Array
(
    [$a] => 1
    [$b] => 2
    [$c] => 3
    [$d] => 3
    [$e] => Array
        (
            [0] => 10
        )

)

 

posted @ 2020-08-05 22:15  一个人的孤独自白  阅读(1065)  评论(0编辑  收藏  举报