数组操作永远不需要 Else

Else is never necessary for an array operation

PHPMD 对以下代码说 'Else is never necessary':

if (!isset($myArray[$myKey])) { // or in_array
    $myArray[$myKey] = $myValue;
} else {
    $myArray[$myKey] += $myValue;
}

是否可以在没有 PHPMD 警告的情况下以更简洁的方式编写此代码?

我知道“? ... : ...”是一个选项,但它仍然是 if/else。

您可以检查是否未设置数组键,如果是,则创建具有默认值的键(如果数组包含数字则为 0,对于字符串则为 '')。这将删除一些重复的代码,例如 $myArray[$myKey] += $myValue;.

if (!isset($myArray[$myKey])) { // or in_array
    $myArray[$myKey] = 0; // if the array contains numbers or '' for string
}
 
$myArray[$myKey] += $myValue;