在本例中,长度变量PHP发生了什么

在本例中,长度变量PHP发生了什么,php,variables,string-length,Php,Variables,String Length,也许这是个愚蠢的问题,但我不明白变量的长度是怎么回事,每一步都发生了什么 $text = 'John'; $text[10] = 'Doe'; echo strlen($text); //output will be 11 为什么var\u dump($text)会显示string(11)“johnd”?为什么它不是一个全名johndoe 有人能解释一下这个时刻吗 // creates a string John $text = 'John'; // a string is an arra

也许这是个愚蠢的问题,但我不明白变量的长度是怎么回事,每一步都发生了什么

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

echo strlen($text);
//output will be 11
为什么
var\u dump($text)
会显示
string(11)“johnd”
?为什么它不是一个全名
johndoe

有人能解释一下这个时刻吗

// 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
要执行您想要的操作,请使用如下连接

$text = 'John';
$text .= ' Doe';
如果你真的想要所有的空间

$text = 'John';
$text .= '      Doe';
或许

$text = sprintf('%s      %s', 'John', 'Doe');
要执行您想要的操作,请使用如下连接

$text = 'John';
$text .= ' Doe';
如果你真的想要所有的空间

$text = 'John';
$text .= '      Doe';
或许

$text = sprintf('%s      %s', 'John', 'Doe');

字符串可以作为数组访问,这就是您使用$text[10]所做的。由于内部工作,所有
$text[10]=“Doe”DO将第11个字符设置为“D”

您必须使用其他类型的字符串连接


字符串可以作为数组访问,这就是您使用$text[10]所做的。由于内部工作,所有
$text[10]=“Doe”DO将第11个字符设置为“D”

您必须使用其他类型的字符串连接


谢谢您的快速回答。你能告诉我为什么它只会添加一个字母,D,为什么不添加整个“Doe”?)它只能添加“D”,因为你只加载了一个事件,即[10],也就是说,
$text[10]
中只有
Doe
的第一个字符的空间,谢谢你的快速回答。你能告诉我为什么它只会添加一个字母,D,为什么不是整个“Doe”?)它只能添加“D”,因为你只加载了一个事件,即[10],即,
$text[10]
中只有
Doe
的第一个字符的空间