I use PHP as a template language in my view layer, Is it possible to make the following a little cleaner and more concise?
//in temp.phtlm <?= (isset($user['name'])) ? $user['name'] : null; ?>
Unfortunately, we can not even define a function for that:
// as you know yet a notice is generated when calling a function with an undefined parameter function echo($var) { return (isset($var)) ? $var : null; }
Advertisement
Answer
Using @
operator is the shortest alternative.
<?= @$user['name']; ?>
Since PHP 7 you can also use the ??
operator.
<?= $user['name'] ?? null; ?>
Which does exactly what the @
operator does, though a bit longer.