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

See this on the PHP 5.3 coalesce function ?::

Coalesce function for PHP?

So you can write:

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

EDIT: As KingCrunch says, you will get this notice:

Notice: Undefined index: ...

, but only if you have configured your system so.

In our PHP codebase we have a custom function coalesce(...) defined, which returns the first alternative for which isset() returns true.


First

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

is not verbosive, it's just complete in what wants it tells you. However, with PHP5.3 you can use the shortcut

$seperator = $options['title-seperator'] ?: ' | ';

But you will get many notices about undefined index keys. I recommend to stay with the first example.

Another (in my eyes) cleaner solution is to introduce default values. Instead of using the options "as they are" merge them with an array of predefined values

$defaults = array(
  'title-separator' => ' | '
);
$options = array_merge ($defaults, $options);

Now you don't need to take care about it and you have all your defaults at one place, instead of scattered all over your code.


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

$first_name = $_POST['f_name'] ?? 'no data found';