-1

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.

tolga
  • 2,462
  • 4
  • 31
  • 57
  • 1
    Maybe you already have an assurance that your array never has that specific key? Context matters, namely how you initialize and use/return your array. Can you share more code? More often that not that rule is advising you that you can rewrite your logic in a more "clean" way. – nitrin0 Oct 27 '21 at 10:08
  • Is phpmd not interfered by error syntax with `$myArray[$myKey]]`? The last `]` is to remove. – RAZAFINARIVO Hanania Oct 27 '21 at 10:09
  • What is $myKey and $myVaue? is it defined? – PHP Hupp Technologies Oct 27 '21 at 10:12
  • Possible bug in MD? As you said, we can use shorthand syntaxes but it is still if-else, like null coalescing operator or ternary operator. – nice_dev Oct 27 '21 at 10:26

1 Answers1

2

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;

  • Good answer, thank you, but I still believe that it's weird to forbid a functionality by all means, which is defined in the language context. – tolga Oct 27 '21 at 11:13
  • 1
    @tolga it's not forbidden and you can ignore it. It's a matter of what that tool defines as a "good practice". Check this [issue](https://github.com/phpmd/phpmd/issues/288) for more details. – nitrin0 Oct 27 '21 at 12:26