3

I am using the answer found at https://stackoverflow.com/a/25749660 in order to sort the $_SERVER['HTTP_ACCEPT_LANGUAGE'] array by the most preferred language.

In that answer (which is working great by the way), one line is:

list($a, $b) = explode('-', $match[1]) + array('', '');

Within PhpStorm, I get the following error for that line:

"Unused local variable $b: The value of the variable is overwritten immediately".

I'm a little confused as to what this line is doing exactly, so I don't know if I should just keep it the same, or if I should modify it to:

list($a) = explode('-', $match[1]) + array('', '');

... which also seems to be working fine.

Should it be changed?

LazyOne
  • 158,824
  • 45
  • 388
  • 391
MultiDev
  • 10,389
  • 24
  • 81
  • 148
  • I think you have incorrect expectations to what `explode() + array()` does. – Havenard Aug 04 '18 at 22:17
  • @Havenard I clearly stated that I am using an answer given in another question and I am unsure as to what that line is doing. That's basically what I'm asking. – MultiDev Aug 04 '18 at 22:19

2 Answers2

0

The wording is confusing because it's a full explanation for an inspection that covers two situations and the initial tooltip only displays the first line, which happens to describe the other situation. If you hit Ctl+F1 you can read the complete text, which kind of makes more sense (emphasis mine):

Unused local variable 'b'. The value of the variable is overwritten immediately. less... (Ctrl+F1)

Inspection info: A variable is considered unused in the following cases:

  • The value of the variable is not used anywhere or is overwritten immediately.
  • The reference stored in the variable is not used anywhere or is overwritten immediately.

That's exactly what happens here:

list($a, $b) = …

$a is used later but $b is not. Since $b is never used, this works as well:

list($a) = explode('-', $match[1]) + array('', '');

(Remember these inspections are hints to prevent potential bugs, not necessarily errors.)

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
-2

You can't join arrays with the arithmetic operator +. Basically you are telling PHP to convert the arrays to scalar types and then sum them, which yields you a number (probably arrays evaluate to 1 if it has elements and 0 if it doesn't).

The result is that effectively you are doing something like:

list($a, $b) = 2;

And the conclusion PHP reaches is that you haven't specified enough elements to define all the variables in the list.

To join two arrays together, use array_merge().

list($a, $b) = array_merge(explode('-', $match[1]), array('', ''));
Havenard
  • 27,022
  • 5
  • 36
  • 62
  • 1
    `+` is also the [**Union** array operator](http://php.net/manual/en/language.operators.array.php). I don't normally use it because I can never remember what rules it follows, but it's indeed overloaded. – Álvaro González Aug 05 '18 at 08:08