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:
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,
)