I have two strings like this
$text = 'Abcdef';
$text[7] = 'Ghijk';
When I take the length of $text by
echo strlen($text);
The answer is 8. Can Any body describe how is it?
In PHP you can access to characters in string like to items in array. So $text[7] = 'Ghijk' add to $text chracter 'G' on 8th position (from zero to seven)
$text = 'Abcdef';
$text[7] = 'Ghijk';
var_dump($text); //outputs string(8) "Abcdef G"
Take a simpler example to see what happens:
$text = 'a';
$text[2] = 'boo'; // now $text is "a b"
When PHP sees that we are accessing index 2 of the string whose length is 1 (with only valid index being 0), it extends the string by adding two spaces, so it makes the string 'a '.
Next the index operator [] deals with characters in the string. So your second statement replaces the 3rd character with a b, giving you a b
Strings are internally implemented as char arrays. When you do something like $text[7] = 'Ghijk'; it applies the first character(as its a char array) in new string i.e. 'G' to 7th place in original string, 6th place in string is empty. Thus making it 8 char long.
chars are 0=>'A' 6=>' ' 7=>'G'
$text[8]='Ghijkl' then the answer should be 9`?$text[7] = 'Ghijk'; adds 'G' at index position 7. As such, when you call echo strlen($text);, the result will be 8 because PHP uses 0-index addressing for strings.
To make more sense of this, consider the following code sample:
$text = 'Abcdef';
echo($text . ' ' . strlen($text) . '<br />');
$text[7] = 'Ghijk';
echo($text . ' ' . strlen($text) . '<br />');
echo($text[7]);
This produces
Abcdef 6
Abcdef G 8
G
The point is the line $text[7] = 'Ghijk'; is only adding 'G'.
$text[7] = 'Ghijk'; should fail, rather than silently adding only 'G' and ignoring the remainder.
echo $textafter$text[7] = 'Ghijk';this line. what it returns?$text[7]it is 6 but after$text[7]it is 8.