Home >Backend Development >PHP7 >Example analysis of the difference between '??' and '?:' introduced in PHP7

Example analysis of the difference between '??' and '?:' introduced in PHP7

coldplay.xixi
coldplay.xixiforward
2020-06-29 18:07:003468browse

Example analysis of the difference between '??' and '?:' introduced in PHP7

##Practice brings true knowledge~

Test code

Input test:

<?php
    $array = [
        &#39;a&#39; => 1,
        &#39;b&#39; => 2,
        &#39;c&#39; => [],
    ];

    $a = $array[&#39;c&#39;] ?? 0;
    $b = $array[&#39;c&#39;] ?: 0;
    $c = $array[&#39;d&#39;] ?? 0;
    $d = $array[&#39;d&#39;] ?: 0;
    $e = $array[&#39;c&#39;] ? 1 : 0;
    $f = isset($array[&#39;c&#39;]) ? 1 : 0;
    $g = $array[&#39;d&#39;] ? 1 : 0;
    $h = isset($array[&#39;d&#39;][&#39;e&#39;]) ? 1 : 0;
    $i = !empty($array[&#39;c&#39;]) ? 1 : 0;
    $j = !empty($array[&#39;d&#39;]) ? 1 : 0;

    var_dump($a);
    var_dump($b);
    var_dump($c);
    var_dump($d);
    var_dump($e);
    var_dump($f);
    var_dump($g);
    var_dump($h);
    var_dump($i);
    var_dump($j);

Output result:

PHP Notice:  Undefined index: d in /home/fanyu/abc.php on line 11PHP Notice:  Undefined index: d in /home/fanyu/abc.php on line 14array(0) {}int(0)int(0)int(0)int(0)int(1)int(0)int(0)int(0)int(0)

Conclusion

  • $a ?? 0 Equivalent to isset($a) ? $a: 0.

  • $a ?: 0 is equivalent to $a ? $a : 0.

  • empty: Determine whether a variable is empty (null, false, 00, 0, '0', ‖ and the like will all return true).

  • isset: Determine whether a variable is set (values ​​such as false, 00, 0, '0', ‖ will also return true).

Related learning recommendations:

PHP programming from entry to proficiency

The above is the detailed content of Example analysis of the difference between '??' and '?:' introduced in PHP7. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete