Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
PHPMD 对以下代码说“永远不需要其他”:
if (!isset($myArray[$myKey])) { // or in_array $myArray[$myKey] = $myValue; } else { $myArray[$myKey] += $myValue; }
是否可以在没有 PHPMD 警告的情况下以更简洁的方式编写此代码?
我知道“?...:...”是一个选项,但它仍然是 if/else。
您可以检查是否未设置数组键,如果是,则使用默认值创建该键(如果数组包含数字,则为 0 或字符串为 '')。这将删除一些重复的代码,例如$myArray[$myKey] += $myValue;.
$myArray[$myKey] += $myValue;
if (!isset($myArray[$myKey])) { // or in_array $myArray[$myKey] = 0; // if the array contains numbers or '' for string } $myArray[$myKey] += $myValue;