Just after a migration to PHP 8, this error appeared; do you know how to resolve this?
PHP Warning: Only the first byte will be assigned to the string offset
It appears for these 2 lines:
if( !isset($value[1]) ) $value[1] = 'NULL' ;
if( !isset($value[2]) ) $value[2] = 'NULL' ;
This is the code around them:
foreach ($chars as $value) {
if( !isset($value[1]) ) $value[1] = 'NULL' ;
if( !isset($value[2]) ) $value[2] = 'NULL' ;
if (!is_null($value[1])) {
$newstring = "?" . $value[1];
}
if ($value[2] !== null) {
$newstring = $newstring . '&' . $value[2];
}
}
The key part of the error message is the phrase "string offset"; it is telling you that $value[1]
is not referring to an element in an array, but a character in a string.
Let's build a minimal example:
$value = 'hello world';
$value[1] = 'NULL' ;
var_dump($value);
Here, $value
is a string, so $value[1]
refers to the character at "string offset 1", which is e
.
We can over-write that character, but only with a different single character. So PHP ignores the ULL
, keeps the N
, and the result is string(11) "hNllo world"
.
The actual behaviour of this code hasn't changed since at least PHP 4.3, the only thing that's new in PHP 8 is the extra message that it's probably not what you meant to do - why would you bother writing 'NULL'
if all you needed was the 'N'
?
In this particular case, it's likely that the original code was expecting $value
to be an array, and is somehow getting a string instead (in the loop shown, $chars
should be an array of arrays, but is an array of strings instead). We can't see the wider context, so have no way of knowing where your fix needs to be.