Is it possible to use the shorthand ternary to check whether a variable is set or not instead of whether is evaluates to zero or non-zero?
For example, I tried:
$var = 0;
echo (string) $var ?: (string) false ?: 2;
But since both the first two expressions evaluate to "0" or "false", 2 is displayed.
I thought that perhaps casting them to a string would produce different results, but it did not. Zero is zero I suppose.
I’m wanting to use this style when assigning variables such as
$get->var = $get->var ?: $setindb ?: $default;
I want to assign $get->var to $get->var if it is set, otherwise, check if the db has a value, otherwise, use a default.
Edit
I thought I would mention that I know I could do something like
$get->var = (!empty($get->var)) ? $get->var : ( (!empty($setindb)) ? $setindb : $default )
But you be the judge at which is simpler 🙂
The string “0” and “false” are considered
FALSE-y (list of false values) values in PHP.isset()returnsTRUEfor variables that are set and notNULL.empty()will check that the variable is set and that is isn’t aFALSEvalue. So it would returnTRUEfor “0”.I think that what you want is your third code snippet, but with
isset(), rather thanempty().The easiest way to do (with the least amount of brackets) that would be:
Since the shorthand tenary returns the first parameter, you can’t use it, because that would be a boolean. (
isset($get->var) ?: $defaultwould returnTRUE,FALSEor$default, but never$get->var‘s value. )Edit: Perhaps you’d like something like a coalesce function? PHP doesn’t offer it natively, as far as I know, but it’s trivial to create. Note that this might be a bit ugly, due to its use of passing references to a function. I’d be interested in comments on this (is it as bad as I think it is?).
I haven’t tested the above. Pass variables in the array as references (
&symbol). I’m pretty sure it’ll choke on something likecoalesce(array(1,"a_string",false));.