在这个例子中,长度变量发生了什么,PHP

Sia*_*ada 0 php variables string-length

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

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

echo strlen($text);
//output will be 11
Run Code Online (Sandbox Code Playgroud)

为什么会var_dump($text)显示string(11) "John D"?为什么它不是全名John Doe

有人可以解释这一刻吗?

Rig*_*lly 5

// 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
Run Code Online (Sandbox Code Playgroud)

要做你想做的事,请使用这样的连接

$text = 'John';
$text .= ' Doe';
Run Code Online (Sandbox Code Playgroud)

如果你真的想要所有的空间

$text = 'John';
$text .= '      Doe';
Run Code Online (Sandbox Code Playgroud)

或者可能

$text = sprintf('%s      %s', 'John', 'Doe');
Run Code Online (Sandbox Code Playgroud)