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

What happened with length variable in this example, PHP

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

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

echo strlen($text);
//output will be 11

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

谁能解释一下这一刻?

// 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[10] 所做的。由于内部运作,$text[10] = 'Doe'; 所做的只是将第 11 个字符设置为 'D'。

您将不得不使用其他类型的字符串连接。

http://php.net/manual/en/function.sprintf.php

可用数据

// Assigns john as a string in variable text
$text = 'John';
$text[10] = 'Doe';

解决方案的概念

这里的关键是要理解字符串可以被视为数组[在这种情况下是字符数组]。

要理解这个就运行:

echo $text[0]

在您的浏览器中,您会注意到输出为 "J"[=​​47=]。

运行

同样,如果你 echo($text[1], $text[2], $text[3]),输出将分别为 "o"、"h"、"n"

现在我们在这里做的是分配 $text[10] as "SAM"。 它将 SAM 视为字符数组(不同的数组)并将 "S" 分配给 $text[10].

因此,从 4 到 9 的所有索引都是空白(在浏览器上打印时为空格)。并且由于任何数组的索引都是从0开始的,所以数组的总长度为11(0,1,2,...,10个索引)。

已解释

想象一下:

[$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