2016-10-04 102 views
0

也許這是愚蠢的問題,但我不明白變量的長度是怎麼回事,每一步發生了什麼?在這個例子中長度變量發生了什麼,PHP

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

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

爲什麼會var_dump($text)顯示string(11) "John D"?爲什麼它不會是一個全名John Doe

有人可以解釋這一刻嗎?

回答

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 

做你想要使用串聯這樣

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

如果你真的希望所有的空間

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

或許

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

謝謝你的回答。你能告訴爲什麼它只會添加一個字母,D,爲什麼不是整個「Doe」?)) – Siada

+1

它只能加上'D',因爲你只加載1個事件,即[10],即只有空間'Doe'的第一個字符'$ text [10]' – RiggsFolly

0

字符串可以訪問什麼作爲數組,這是你在用$ text做什麼[10]。由於內部工作原因,所有$text[10] = 'Doe';確實將第11個字符設置爲'D'。你將不得不使用其他類型的字符串連接

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