Reputation: 47
Maybe this is stupid question but I don't understand what is going on with the length of variable, what is happening in each step?
$text = 'John';
$text[10] = 'Doe';
echo strlen($text);
//output will be 11
Why will var_dump($text)
display string(11) "John D"
? Why will it not be a full name John Doe
?
Can someone explain this moment?
Upvotes: 0
Views: 758
Reputation: 127
Available data
// Assigns john as a string in variable text
$text = 'John';
$text[10] = 'Doe';
Concept of Solution
The catch here is to understand that the strings can be treated as a array [array of characters in this case].
To understand this just run:
echo $text[0]
in your browser, you will notice that the output is "J".
RUN
Similarly if you echo($text[1], $text[2], $text[3])
, the output will be "o", "h", "n" respectively.
Now what we ae doing here is assigning $text[10] as "SAM"
.
It treats SAM as an array(different array) of characters and assigns "S"
to $text[10]
.
So what happens is all the indexes from 4 to 9 are blank (blank spaces when printed on browser). And as the index of any array starts from 0, the total length of the array is 11 (0, 1, 2,..., 10 indexes).
EXPLAINED
Imagine it like this:
[$variable[$index] = $value]
$text[0] = J
$text[1] = o
$text[2] = h
$text[3] = n
$text[4] =
$text[5] =
$text[6] =
$text[7] =
$text[8] =
$text[9] =
$text[10] = S
echo $text;
// output in browser: "John D";
// actual output: "John D";
echo strlen($text);
// output: 11
Upvotes: 0
Reputation: 94682
// creates a string John
$text = 'John';
// a string is an array of characters in PHP
// So this adds 1 character from the beginning of `Doe` i.e. D
// to occurance 10 of the array $text
// It can only add the 'D' as you are only loading 1 occurance i.e. [10]
$text[10] = 'Doe';
echo strlen($text); // = 11
echo $text; // 'John D`
// i.e. 11 characters
To do what you want use concatenation like this
$text = 'John';
$text .= ' Doe';
If you really want all the spaces
$text = 'John';
$text .= ' Doe';
Or maybe
$text = sprintf('%s %s', 'John', 'Doe');
Upvotes: 5
Reputation: 1410
Strings can be accessed as arrays, which is what you're doing with $text[10]. Because of the internal workings, all $text[10] = 'Doe';
does is set the 11th character to 'D'.
You will have to use some other kind of string concatenation.
http://php.net/manual/en/function.sprintf.php
Upvotes: 0