我在阅读关于PHP中三元运算符和空值合并运算符的相关内容,并进行了一些实验。
因此,你可以使用三元运算符和空值合并运算符的方式来代替这种写法:
if (isset($array['array_key']))
{
$another_array[0]['another_array_key'] = $array['array_key'];
}
else
{
// Do some code here...
}
我尝试使用 null coalescing 进一步缩短代码,而不是使用 null coalescing 或三目运算符来缩短它,但没有包含 'else' 部分,因为我并不需要。我搜索了一些解决方案,但都不是我想要的。
我尝试了这个方法,两种解决方案都可行!
$another_array[0]['another_array_key'] = $array['array_key'] ??
$another_array[0]['another_array_key'] = $array['array_key'] ? :
print_r($another_array);
注意上面那行代码末尾没有分号。 我的问题是:这段代码是否可接受?我认为用注释解释它可能会影响代码的可读性。 如果这是一个类似的问题,抱歉 - 我没有时间检查所有问题,因为Stack Overflow提供了相当多的建议。 以下是完整的代码示例:“
<?php
$another_array = [];
$array = [
'name' => 'Ivan The Terrible',
'mobile' => '1234567890',
'email' => 'tester@test.com'
];
if (isset($array['name']))
{
$another_array[0]['full_name'] = $array['name'];
}
$another_array[0]['occupation'] = $array['occupation'] ??
// or $another_array[0]['occupation'] = $array['occupation'] ? :
print_r($another_array);
?:
与??
不等同。如果数组中不存在该键,则第一个将导致PHP Notice
。 - Yoshi