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.
PHP 7 has introduced Null Coalescing operator in which you can use like
$first_name = $_POST['f_name'] ?? 'no data found';
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With