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

Juha Untinen picture Juha Untinen · Apr 12, 2013 · Viewed 13.5k times · Source

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:

<?php
    if(!empty($this->variable)) {
        echo '<a href="', $this->variable, '">Link</a>';
    }
?>

I'm thinking about something in the lines of this C-style pseudocode:

<?php
    echo if(!empty($this->variable, '<a href="', %s, '">Link</a>'));
?>

PHP has sprintf, but it doesn't quite do what I was hoping for. If course I could make a method/function out of it, but surely there must be a way to do it "natively"?

Update: Ternary operations would also repeat the $this->variable part, if I understood it?

echo (!empty($this->variable) ? '<a href="',$this->variable,'">Link</a> : "nothing");

Answer

German Rumm picture German Rumm · Apr 12, 2013

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: '';