如果某个变量在 PHP 中不存在,是否有一种简便的方法来为它赋值?
if(!isset($var) { $var = ""; }
我想做一些像
$var = $var | "";
Update for PHP 7 (thanks shock_gone_wild)
PHP 7 introduces the null coalescing operator which simplifies the below statements to:
$var = $var ?? "default";
Before PHP 7
No, there is no special operator or special syntax for this. However, you could use the ternary operator:
$var = isset($var) ? $var : "default";
Or like this:
isset($var) ?: $var = 'default';
PHP 7.4+; with the null coalescing assignment operator
$var ??= '';
PHP 7.0+; with the null coalescing operator
$var = $var ?? '';
PHP 5.3+; with the ternary operator shorthand
isset($var) ?: $var = '';
Or for all/older versions with isset:
$var = isset($var) ? $var : '';
or
!isset($var) && $var = '';