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

前端 未结 3 756
眼角桃花
眼角桃花 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:19

    Use isset function of php like this:

    <?php
    
      echo $result = isset($this->variable) ? $this->variable : "variable not set";
    
     ?>
    

    i think this will help.

    0 讨论(0)
  • 2021-02-13 22:30

    Update:

    PHP 7 introduces a new feature: Null coalescing operator

    Here is the example from php.net.

    <?php
    // Fetches the value of $_GET['user'] and returns 'nobody'
    // if it does not exist.
    $username = $_GET['user'] ?? 'nobody';
    // This is equivalent to:
    $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
    
    // Coalescing can be chained: this will return the first
    // defined value out of $_GET['user'], $_POST['user'], and
    // 'nobody'.
    $username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
    ?>
    

    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,
    )
    
    0 讨论(0)
  • 2021-02-13 22:39

    The closest you can get to what you are looking for is using short form of ternary operator (available since PHP5.3)

    echo $a ?: "not set"; // will print $a if $a evaluates to `true` or "not set" if not
    

    But this will trigger "Undefined variable" notice. Which you can obviously suppress with @

    echo @$a ?: "not set";
    

    Still, not the most elegant/clean solution.

    So, the cleanest code you can hope for is

    echo isset($a) ? $a: '';
    
    0 讨论(0)
提交回复
热议问题