【问题标题】:Omitting the 'else' in PHP ternary and null coalescing operators [closed]在 PHP 三元和空合并运算符中省略“else”[关闭]
【发布时间】:2020-01-17 13:02:14
【问题描述】:

我正在阅读并尝试使用 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);

【问题讨论】:

  • 您已经回答了自己的问题。如果您希望代码可维护,请编写源代码供他人阅读,而不是您自己阅读。
  • 关于“注意上面一行的末尾没有;。”:这可能使它在几乎所有情况下都无效,并在所有其他情况下产生意想不到的结果。这意味着您需要在那里放一些东西,使其更具可读性。
  • 另请注意,?: 不等同于 ??。如果数组中不存在该键,第一个将导致PHP Notice
  • “两种解决方案都有效” - 你错了,首先考虑这 两个 事情。这在没有分号的情况下有效,因为整个事情都被认为是 one 表达式。 (换行符在这里没有语法意义,它们不会像其他语言那样将其分成多个单独的表达式。)
  • 谢谢@Cid。我已经在那里添加了示例。

标签: php readability code-readability


【解决方案1】:

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

<?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'] =&gt; true 因为the return value of print_r()

【讨论】:

猜你喜欢
  • 2020-06-22
  • 2018-07-05
  • 2018-03-12
  • 1970-01-01
  • 2021-09-26
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
相关资源
最近更新 更多