php - 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?

Answer

Solution:

There is an operator in PHP(from version 7.0) called null coleascing operator which is denoted by two question marks(??). Null colescing operator can be helpful in your case. For example, you can simply write this code as below:

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

which is equavalent to writing:

<?= isset($debate['title']) ? $debate['title'] : '' ?>

Hope this helps.

Source