If null use other variable in one line in PHP

前端 未结 12 706
说谎
说谎 2020-12-29 01:47

Is there in PHP something similar to JavaScript\'s:

alert(test || \'Hello\');

So, when test is undefined or null we\'ll see Hello, otherwis

相关标签:
12条回答
  • 2020-12-29 02:32

    Null is false in PHP, therefore you can use ternary:

    alert($test ? $test : 'Hello');
    

    Edit:

    This also holds for an empty string, since ternary uses the '===' equality rather than '=='

    And empty or null string is false whether using the '===' or '==' operator. I really should test my answers first.

    0 讨论(0)
  • 2020-12-29 02:34

    As per the latest version use this for the shorthand

    $var = $value ?? "secondvalue";
    
    0 讨论(0)
  • 2020-12-29 02:40

    I'm very surprised this isn't suggested in the other answers:

    echo isset($test) ? $test : 'hello';
    

    From the docs isset($var) will return false if $var doesn't exist or is set to null.

    The null coalesce operator from PHP 7 onwards, described by @Yamiko, is a syntax shortcut for the above.

    In this case:

    echo $test ?? 'hello'; 
    
    0 讨论(0)
  • 2020-12-29 02:41

    you can do echo $test ?: 'hello';

    This will echo $test if it is true and 'hello' otherwise.

    Note it will throw a notice or strict error if $test is not set but...

    This shouldn't be a problem since most servers are set to ignore these errors. Most frameworks have code that triggers these errors.


    Edit: This is a classic Ternary Operator, but with the middle part left out. Available since PHP 5.3.

    echo $test ? $test : 'hello'; // this is the same
    echo $test ?: 'hello';        // as this one
    

    This only checks for the truthiness of the first variable and not if it is undefined, in which case it triggers the E_NOTICE error. For the latter, check the PHP7 answer below (soon hopefully above).

    0 讨论(0)
  • 2020-12-29 02:41

    From PHP 7 onwards you can use something called a coalesce operator which does exactly what you want without the E_NOTICE that ?: triggers.

    To use it you use ?? which will check if the value on the left is set and not null.

    $arr = array($one ?? 'one?', $two ?? 'two?'); 
    
    0 讨论(0)
  • 2020-12-29 02:46

    If you want to create an array this way, array_map provides a more concise way to do this (depending on the number of elements in the array):

    function defined_map($value, $default) {
        return (!isset($value) || is_null($value)) ? $default : $value;
        // or return $value ? $default : $value;
    }
    
    $values = array($one, $two);
    $defaults = array('one', 'two');
    
    $values = array_map('defined_map', $values, $defaults);
    

    Just make sure you know which elements evaluate to false so you can apply the right test.

    0 讨论(0)
提交回复
热议问题