Search code examples
phpphp-8

Warning: Only the first byte will be assigned to the string offset


The following code was working just fine in PHP 7 so why am I seeing this warning in PHP 8?

$str = 'xy';
$str[0] = 'bc';

Solution

  • As of PHP 8 trying to replace a string offset with more than one byte using square array brackets style will emit a warning.

    So you just need to remove the extra byte (c in this case)

    $str = 'xy';
    $str[0] = 'b';
    

    Or if you really want to replace x with bc you can use substr_replace

    $str = 'xy';
    var_dump(substr_replace($str, 'bc', 0, 1)); // output: string(2) "bcy"
    

    Note: this function accepts byte offsets, not code point offsets.