Cannot assign an empty string to a string offset

Description

It is possible to access an individual character inside a string, and replace it with another character.

On the other hand, it is not possible to remove that character by using an empty string. The only allowed modification is a replacement: one character replace another character.

In fact, PHP will only use the first character, when trying to modify an offset with a string longer than one character.

Example

<?php

$string = 'ab d';
$string[2] = 'c';  // add c in the right place

$string[2] = '';  // error

$string[2] = 'Cdef';  // only sets the c

?>

Solutions

  • Use substr() to cut the string before and after, then concatenate them.

  • Replace the character with a space.