Home > Backend Development > PHP7 > body text

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

coldplay.xixi
Release: 2023-02-17 16:50:01
forward
3210 people have browsed it

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

##Practice brings true knowledge~

Test code

Input test:

 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);
Copy after login

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)
Copy after login

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!

Related labels:
php
source:csdn.net
Statement of this Website
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 [email protected]
Latest issues
Popular Tutorials
More>
Latest downloads
More>
web effects
Website source code
Website materials
Front end template
About us Disclaimer Sitemap
PHP Chinese website:Public welfare online PHP training,Help PHP learners grow quickly!