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

前端 未结 3 744
眼角桃花
眼角桃花 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: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: '';
    

提交回复
热议问题