-1

Since PHP 8 the following triggers a "Undefined array key ..." warning:

list($a, $b) = explode(',', 'foo');
if(!$b) {
  // ...
}

I know that i can refactor this like ...

$arr = explode(',', 'foo');
$a = $arr[0] ?? null;
$b = $arr[1] ?? null;
if(!$b) {
  // ...
}

... but I sense there is a more elegant way. Is there?

  • 2
    `explode()` expects two string arguments (and an optional limit), but your second argument is an array. What are you trying to do with this piece of code? – Rob Eyre May 02 '23 at 13:41
  • 2
    I would personally just not create a variable for every element in an array, as that kind of defeats the purpose of the array imo, and makes the code harder to read and debug. I would rather just use a string as a key – GrumpyCrouton May 02 '23 at 13:44
  • Your example only uses `$b` -- if that's all you need, then you can reference the call to explode directly as an array: `if (!(explode(',', 'foo')[1] ?? null)) { ... }` – Alex Howansky May 02 '23 at 14:15
  • 1
    If you need both `$a` and `$b` set, then just manually add an explicit separator character to the end of the string before exploding it, this will give you a minimum of two values in the split in the cases where the string doesn't already contain a separator: `[$a, $b] = explode(',', $string . ',');` – Alex Howansky May 02 '23 at 14:22

1 Answers1

-1

Why not simply this:

$arr = explode(',', 'foo');
if(empty($arr[1])) {
  // ...
}

(which replicates your current logic).

However, if you wanted to be more strict you could use this:

$arr = explode(',', 'foo');
if(!array_key_exists(1, $arr)) {
  // ...
}

If you prefer to keep using list and the variables $a and $b, then you could use

list($a, $b) = array_pad(explode(',', 'foo'), 2, null);
if (!$b) {
  // ...
}
Rob Eyre
  • 717
  • 7
  • Good point but "list" is used for a reason and it should be in the future. Also I don't want to refactor my enire code uppon PHP migration, so the variables should stay. In addition, using numeric keys is not all that "better readable" if it gets more complex than the example shows. – gartenumgraben May 02 '23 at 14:05
  • Fair point. In that case you might find that `list($a, $b) = array_pad(explode(',', 'foo'), 2, null); if (!$b) { ...` is a useful replacement to your code – Rob Eyre May 02 '23 at 14:12