首页 > 解决方案 > 省略 PHP 三元和空值合并运算符中的“else”

问题描述

我正在阅读并尝试使用 PHP 中的三元和空值合并运算符。

所以,而不是写

if (isset($array['array_key']))
{
    $another_array[0]['another_array_key'] = $array['array_key'];
}
else
{
    // Do some code here...
}

而不是使用空合并或三元运算符缩短它,我尝试使用空合并进一步缩短代码,但没有'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);

标签: phpreadabilitycode-readability

解决方案


可重复性、可维护性...如果您想测试许多可能的数组键,然后将它们添加或不添加到最终数组中,没有什么能阻止您创建第三个数组,该数组将保存键以检查和循环遍历它:

<?php

$another_array = [];

$array = [
    'name' => 'Ivan The Terrible',
    'mobile' => '1234567890',
    'email' => 'tester@test.com'
];

$keysToCheck = [
    // key_in_the_source_array => key_in_the_target
    'name' => 'full_name',
    'occupation' => 'occupation'
    // if you want to test more keys, just add them there
];

foreach ($keysToCheck as $source => $target)
{
    if (isset($array[$source]))
    {
         $another_array[0][$target] = $array[$source];
    }
}

print_r($another_array);

请注意

$another_array[0]['occupation'] = $array['occupation'] ??

print_r($another_array);

被评估为

$another_array[0]['occupation'] = $array['occupation'] ?? print_r($another_array);

如果你在print_r($another_array);之后添加另一个,你会注意到$another_array[0]['occupation'] => true因为返回值print_r()


推荐阅读