I\'ve been coding personal scripts for years in PHP and get used to turn off Error display. I\'m about to release some of these scripts and would like to do it the proper way.>
Your if()
with isset()
attempt is the proper way of doing that!
But you can write it a little bit shorter/more readable, using the Ternary Operator:
$foo = isset($foo) ? $foo : '';
The first $foo
will be set to the value after the ?
when the condition after the =
is true, else it will be set to the value after the :
. The condition (between =
and ?
) will always be casted as boolean.
Since PHP 5.3 you can write it even shorter:
$foo = isset($foo) ?: '';
This will set $foo
to TRUE
or FALSE
(depending on what isset()
returns), as pointed by @Decent Dabbler in the comments. Removing isset()
will set it to ''
but it will also throw an undefined variable notice (not in production though).
Since PHP 7 you can use a null coalesce operator:
$foo = $foo ?? '';
This won't throw any error, but it will evaluate as TRUE
if $foo
exists and is empty, as opposed to the shorthand ternary operator, that will evaluate as FALSE
if the variable is empty.