After the code below is executed, what will be the value of $text and what will strlen($text) return? Explain your answer.

$text = 'John ';
$text[10] = 'Doe';


After the above code is executed, the value of $text will be the string “John D” (i.e., “John”, followed by 5 spaces, followed by “D”) and strlen($text) will return 11.

There are two things going on here.

First of all, since $text is a string, setting a single element of $text simply sets that single character to the value specified. The statement $text[10] = 'Doe' therefore sets that single character to 'D' (i.e., the first character in the string "Doe", since an element of a string can only be a single character).

Secondly, $text[10] = 'Doe' says to set the 11th character of the string (remember that indices are zero-based) to 'D'. Prior to that statement, though, the length of the string $text ("John ") was only 5. Whereas compilers or interpreters in other languages might barf (with something akin to an out-of-bounds-index error) when you then attempt to set the 11th character of a 5 character string, PHP instead is very “accommodating” and instead allows this and sets all intermediate characters to blanks.


© 2017