2016-10-04 4 views
0

これは愚かな質問かもしれませんが、変数の長さがどうなっているのか分かりません。この例の長さ変数で何が起こったのですか?

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

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

はなぜ表示string(11) "John D"var_dump($text)でしょうか?なぜそれは完全な名前ではないでしょうJohn Doe

この瞬間を誰かが説明できますか?あなたはこの

$text = 'John'; 
$text .= ' 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 = sprintf('%s  %s', 'John', 'Doe'); 
+0

ありがとうございました。 )なぜなら、 "Doe"全体ではなく、1つの文字Dを追加する理由を教えてください。) – Siada

+1

1つの出現[10]しかロードしていないので、 'D' 'Doe'の最初の文字の' $ text [10] ' – RiggsFolly

0

をしたい場合は文字列は、アクセスすることができます配列として、 $ text [10]でやっていること。内部的な処理のため、$text[10] = 'Doe';はすべて11番目の文字を 'D'に設定します。

他の種類の文字列連結を使用する必要があります。

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

関連する問題