Best way to give a variable a default value (simulate Perl ||, ||= )

后端 未结 8 1406
眼角桃花
眼角桃花 2020-12-07 11:46

I love doing this sort of thing in Perl: $foo = $bar || $baz to assign $baz to $foo if $bar is empty or undefined. You al

8条回答
  •  悲哀的现实
    2020-12-07 12:37

    In PHP 7 we finally have a way to do this elegantly. It is called the Null coalescing operator. You can use it like this:

    $name = $_GET['name'] ?? 'john doe';
    

    This is equivalent to

    $name = isset($_GET['name']) ? $_GET['name']:'john doe';
    

提交回复
热议问题