Home >Backend Development >PHP7 >What is the difference between '??' and '?:' in PHP7?

What is the difference between '??' and '?:' in PHP7?

PHPz
PHPzforward
2020-09-25 15:57:513696browse

What is the difference between '??' and '?:' in PHP7?

Recommended tutorial: "PHP7"

Practice brings true knowledge~

Test code

Input test :

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

    $a = $array['c'] ?? 0;
    $b = $array['c'] ?: 0;
    $c = $array['d'] ?? 0;
    $d = $array['d'] ?: 0;
    $e = $array['c'] ? 1 : 0;
    $f = isset($array['c']) ? 1 : 0;
    $g = $array['d'] ? 1 : 0;
    $h = isset($array['d']['e']) ? 1 : 0;
    $i = !empty($array['c']) ? 1 : 0;
    $j = !empty($array['d']) ? 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 11
PHP Notice:  Undefined index: d in /home/fanyu/abc.php on line 14
array(0) {
}
int(0)
int(0)
int(0)
int(0)
int(1)
int(0)
int(0)
int(0)
int(0)

Conclusion

  1. ##$a ?? 0 is equivalent to isset($a) ? $a : 0.

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

  3. empty: Determine whether a variable is empty (null, false, 00, 0, ‘0’0′, ‖ and the like will all return true).

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

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of What is the difference between '??' and '?:' 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