PHPMD says 'Else is never necessary' for the following code:
if (!isset($myArray[$myKey])) { // or in_array
$myArray[$myKey] = $myValue;
} else {
$myArray[$myKey] += $myValue;
}
Is it possible to write this code in a cleaner way without a PHPMD warning?
I know "? ... : ..." is an option but it's still if/else.
You can check if the array key is not set if so create that key with a default value (0 if the array holds numbers or '' for string ). This will remove some duplicate code like $myArray[$myKey] += $myValue;
.
if (!isset($myArray[$myKey])) { // or in_array
$myArray[$myKey] = 0; // if the array contains numbers or '' for string
}
$myArray[$myKey] += $myValue;