Search code examples
phpphp-7php-7.4

How do I print an array value as a template tag as blank in shorthand, even if it's null?


If I have this in my main php file (eg. my controller)

$debate['title'] = NULL;

And this in my template file (eg. my views file), where I can include PHP with my HTML. Imagine that I'm using a template engine or PHP as a templating engine.

<?=$debate['title'];?>

Note the = after the <? that makes it a shorthand way to include php variables and array keys in my template, to be shown on an HTML web page.

Well now in PHP 7.4 onwards, if $debate['title'] is null, I get this error. (That's if the notice severity level of errors is setup to be displayed on your screen.)

Message: Trying to access array offset on value of type null

I know that Stack Overflow would want me to use isset() but using something like

<?php if (isset($debate['title'])) { echo "$debate[title]"; } ?>

It just doesn't have the same ring to it. It's not really shorthand, is it?


Solution

  • In general you can use the null coalescing operator, like

    $debate['title'] ?? ''
    

    If you pass this to a function, then you can apply the same inside the function parameters, like:

    htmlspecialchars($debate['question'] ??  'array is blank');