I have a string with an operator in:
echo 'abc.' . $type ?? 'no type' . 'xyz';
If $type exists I want that to be the value, if it does not, I want 'no type' to be the value.
But with the above I just get a $type undefined error. It's not defined in my example as I want 'no type' to be outputted.
Where am I going wrong?
echo 'abc.' . ($type ?? 'no type') . 'xyz';
or this (ternary operator)
echo 'abc.' . (isset($type) ? $type : 'no type' ) . 'xyz';
You need to add brackets round the ?? operator...
echo 'abc.' . ($type ?? 'no type') . 'xyz';
What it was doing was evaluating it like 'abc.' . $type
and then ??
.
This is all about operator precedence (thanks to @Blackhole for the prompt).
You don't need to use concatenation when using echo
. It can take multiple arguments, just separate them with a comma (as if it were an actual function):
echo 'abc.', $type ?? 'no type', 'xyz';
This is also (slightly) more efficient than the upvoted answer, especially with long strings (PHP doesn't have to construct/store the whole string in a buffer before displaying it).