Skip to content
Advertisement

How to assign a variable to one of two strings if one is blank?

I am wondering why this doesn’t work to assign a string to $separator:

$separator = $options['title-separator'] || ' | ';

Elsewhere, $option has been assigned to some text or an empty string. (Actually, in my real life case, it’s some text, or FALSE, but either way…). $separator is TRUE instead of a string.

The following accomplishes what I want, but seems unnecessarily verbose:

$separator = ( $s = $options['title-separator'] ) ? $s : ' | ';

I come from JavaScript, where both these examples have the same result, which seems logical to me. What do I need to understand about PHP for this to make sense? Right now, I’m just annoyed by the hundreds of extra characters this will require for every place an option gets used.

Advertisement

Answer

PHP 7 has introduced Null Coalescing operator in which you can use like

$first_name = $_POST['f_name'] ?? 'no data found';
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement