简体   繁体   English

PHP 或空变量的简写

[英]PHP or shorthand for empty variable

$a = '';
$b = 1;

How to print $b if $a = '' using shorthand in PHP?如果 $a = '' 在 PHP 中使用速记如何打印 $b?

in javascript there is something like在javascript中有类似的东西

a || b; 

Ternary Operator 三元运算符

$a = '';
$b = 1;

echo $a ?: $b; // 1

Until $a is evaluated false, $b will be displayed.在 $a 被评估为 false 之前,将显示 $b。 Remember that the following things are considered to be empty :请记住,以下内容被认为是空的

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

That means that if $a is "", 0, "0", null, false, array(), .. then $b will be displayed.这意味着如果 $a 是 "", 0, "0", null, false, array(), .. 那么 $b 将被显示。 See PHP type comparison tables .请参阅PHP 类型比较表

If you want to display $b only when $a is an empty string, then you should uses strict comparison operators (===)如果只在 $a 为空字符串时才显示 $b,则应使用严格比较运算符 (===)

$a = '';
$b = 1;

echo $a === '' ? $b : ''; // 1

This is the shorthand for an IF/Else statement in PHP.这是 PHP 中IF/Else语句的简写。

echo ($a != '' ? $a : $b)

If $a is not an empty string output (echo) $a otherwise output $b.如果$a不是空字符串输出 (echo) $a否则输出 $b。

As others ahve said Turnary operator is handy for most senarios.正如其他人所说,Turnary 运算符对大多数 senario 来说都很方便。

echo $a ?: $b;//b

But it is NOT shorthand for empty().但它不是 empty() 的简写。 Ternary operator will issue notices if var/array keys/properties are not set.如果未设置 var/array 键/属性,则三元运算符将发出通知。

echo $someArray['key that doesnt exist'] ?: $b;//Notice: Undefined index
echo $arrayThatDoesntExist['key-that-doesnt-exist'] ?: $b;//Notice: Undefined variable

empty() will take care of the additional checks for you and its recomended to just use it. empty() 将为您处理额外的检查,建议您只使用它。

if (empty($arrayThatDoesntExist['key-that-doesnt-exist'])) echo $b;

You could technically just suppress the warning/notice with @ and the ternary operator becomes a replacement for empty().从技术上讲,您可以使用 @ 来抑制警告/通知,而三元运算符将替代 empty()。

@echo $someArray['key that doesnt exist'] ?: $b;
@echo $arrayThatDoesntExist['key-that-doesnt-exist'] ?: $b;

But usually not recommended as supressing notices and warnings could lead you into trouble later on plus I think it may have some performance impact.但通常不推荐,因为抑制通知和警告可能会导致您以后遇到麻烦,而且我认为它可能会对性能产生一些影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM