PHP: in-line default value for variables,
Use less code to do what you need.
You don't need to specify the variable again using the _?_:_
format.
echo $var?:"default";
Is the same as
echo $var?$var:"default";
Now as far as an empty check, you could use @
to mute notices, I'm not sure of the technical ramifications, but you're already doing your own checking while using this format:
echo @$non_existing_var?:"default";
Some examples:
<?php
$nope = null;
$yup = "hello";
echo ($nope?:$yup) . "\n" ;
echo ($yup?:$nope) . "\n" ;
$items = [ 'one', 'two', false, 'three', 'four', null ];
foreach($items as $item):
echo($item?:"default shown (".var_export($item,true).")")."\n";
endforeach;
echo(@$non_existing?:"default for non-existant variable!");
?>
Output:
$ php variabledefault.php
hello
hello
one
two
default shown (false)
three
four
default shown (NULL)
default for non-existant variable!%
Written by Larry Williamson
Related protips
3 Responses
Nice
over 1 year ago
·
You shouldn't mask your errors with @
, that's bad practice. Just write your code correctly.
over 1 year ago
·
It is a matter of opinion and project really. I'm not saying to write code like this for everything. It's a tip not a rule.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#