Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 238
Greg Perham Avatar asked Jan 15 '12 20:01

Greg Perham


4 Answers

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

$first_name = $_POST['f_name'] ?? 'no data found';
like image 76
Ankur Kumar Singh Avatar answered Nov 17 '22 17:11

Ankur Kumar Singh


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.

like image 20
KingCrunch Avatar answered Nov 17 '22 17:11

KingCrunch


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.

like image 5
The Nail Avatar answered Nov 17 '22 17:11

The Nail


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

Because the language is not defined that way....

The definition of the || operator says that $a || $b returns TRUE if either $a or $b is TRUE, not that it returns $a if $a evaluates to TRUE.

like image 3
MZB Avatar answered Nov 17 '22 15:11

MZB