If null use other variable in one line in PHP

前端 未结 12 705
说谎
说谎 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:21
    alert((test == null || test == undefined)?'hello':test);
    
    0 讨论(0)
  • 2020-12-29 02:21

    I recently had the very same problem.This is how i solved it:

    <?php if (empty($row['test'])) {
                        echo "Not Provided";} 
                            else {
                        echo $row['test'];}?></h5></span></span>
                  </div>
    

    Your value in the database is in variable $test..so if $test row is empty then echo Not Provided

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

    There may be a better way, but this is the first thing that came to my mind:

     echo (!$test) ? "Hello" : $test;
    
    0 讨论(0)
  • 2020-12-29 02:24

    One-liner. Super readable, works for regular variables, arrays and objects.

    // standard variable string
    $result = @$var_str ?: "default";
    
    // missing array element
    $result = @$var_arr["missing"] ?: "default";
    
    // missing object member
    $result = @$var_obj->missing ?: "default";
    

    See it in action: Php Sandbox Demo

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

    See @Yamiko's answer below for a PHP7 solution https://stackoverflow.com/a/29217577/140413

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

    Or you can be a little more robust and do this

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

    Well, expanding that notation you supplied means you come up with:

    if (test) {
        alert(test);
    } else {
        alert('Hello');
    }
    

    So it's just a simple if...else construct. In PHP, you can shorten simple if...else constructs as something called a 'ternary expression':

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

    Obviously there is no equivalent to the JS alert function in PHP, but the construct is the same.

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