Check if variable is set and then echo it without repeating?

前端 未结 3 748
眼角桃花
眼角桃花 2021-02-13 21:48

Is there a concise way to check if a variable is set, and then echo it without repeating the same variable name?

Instead of this:



        
3条回答
  •  深忆病人
    2021-02-13 22:30

    Update:

    PHP 7 introduces a new feature: Null coalescing operator

    Here is the example from php.net.

    
    

    For those not using PHP7 yet here is my original answer...

    I use a small function to achieve this:

    function ifset(&$var, $else = '') {
      return isset($var) && $var ? $var : $else;
    }
    

    Example:

    $a = 'potato';
    
    echo ifset($a);           // outputs 'potato'
    echo ifset($a, 'carrot'); // outputs 'potato'
    echo ifset($b);           // outputs nothing
    echo ifset($b, 'carrot'); // outputs 'carrot'
    

    Caveat: As Inigo pointed out in a comment below one undesirable side effect of using this function is that it can modify the object / array that you are inspecting. For example:

    $fruits = new stdClass;
    $fruits->lemon = 'sour';
    echo ifset($fruits->peach);
    var_dump($fruits);
    

    Will output:

    (object) array(
      'lemon' => 'sour',
      'peach' => NULL,
    )
    

提交回复
热议问题