我必须编写很多这样的代码:
if ( !empty($value['fax'])) {
$temp['fax'] = $value['fax'];
} else {
$temp['fax'] = "unknown";
}
只是想知道是否有更短的版本...
答案 0 :(得分:3)
查看a similar answer I wrote on the subject:
def pentaSquares(n):
squarlist=[]
pentalist=[]
squares = lambda x:x*x
penta = lambda y:y*(3*y-1)//2
for i in range(n):
squarlist.append(squares(i))
pentalist.append(penta(i))
l=[x for x in squarlist if x in pentalist]
if l < 4:
print('there are less than 4 values, input larger n')
return l
如果您实际上正在检查$temp['fax'] = (!empty($value['fax'])) ? $value['fax'] : 'unknown';
或isset()
而非is_null()
(其中包括empty()
,null
,false
,{{ 1)})然后在PHP 7中:
0
答案 1 :(得分:2)
PHP7 +解决方案(Null coalesce operator):
$temp['fax'] = $value['fax'] ?? 'unknown';
答案 2 :(得分:1)
使用三元运算符:
$temp['fax'] = !empty($value['fax']) ? $value['fax'] : 'unknown'