Home > Enterprise >  php 8.1 explode causes error when result is assigned to list
php 8.1 explode causes error when result is assigned to list

Time:07-27

I'm using PHP 8.1 and I'm getting an error when splitting on something that is not in the string. This was not a problem with PHP 7.4.

$str = "This string has no dash";
list($a, $b) = explode('-', $str, 2);

Error : Undefined array key 1

The manual does not mention this behavior. https://www.php.net/manual/en/function.explode.php

So what is going on?

CodePudding user response:

$str = "This string has no dash";
if (strpos($str, '-') !== false) {
  list($a, $b) = explode('-', $str, 2);
} else {
  $a = $str;
  $b = '';
}

CodePudding user response:

The issue is that explode will produce a single element so you can't destruct the result array in two variables.

The error here is pretty clear: $b is trying to take a value from array[1] where array is explode result. As no dashes are contained inside $str, explode produce a single element, as stated before.

As you may not know how many element will be produced by explode, I would suggest not to use array destructuring for this kind of operation unless you're really sure about result count.

  • Related