1

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?

2
  • Try echo $text after $text[7] = 'Ghijk'; this line. what it returns? Commented Feb 8, 2012 at 11:11
  • I have echoed after this line. the result is of two lines. Before $text[7] it is 6 but after $text[7] it is 8. Commented Feb 8, 2012 at 11:15

4 Answers 4

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

This is strange na? Even if it is considering the $text as array even then it should add the whole sting not only G
1

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

Comments

1

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'

1 Comment

and it is creating the 7th character of white space as its own? If we will give $text[8]='Ghijkl' then the answer should be 9`?
1

$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'.

3 Comments

This is strange na? Even if it is considering the $text as array even then it should add the whole sting not only G
It's a char array, not a string array - when you add the 'G', the array length (strlen) is 8.
PHP, IMO is too lax here. $text[7] = 'Ghijk'; should fail, rather than silently adding only 'G' and ignoring the remainder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.