Proper way to declare multiple vars in PHP
<?php
$foo = $bar = $ping = $pong = '';
?>
If it's your script and you know which variables where you use, why you want spend recourses to check if the variable was declared before?
I posted this in a comment earlier, but someone suggested I submit it as an answer.
The shortest and simplest way I can think of, is to do:
$foo = $bar = $ping = $pong = '';
I often prefer to set things to false, instead of an empty string, so that you can always do checks in the future with === false, but that is just a preference and depends on how you are using these variables and for what.
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.