Search code examples
phpvariablesstring-length

What happened with length variable in this example, PHP


Maybe this is stupid question but I don't understand what is going on with the length of variable, what is happening in each step?

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

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

Why will var_dump($text)display string(11) "John D"? Why will it not be a full name John Doe?

Can someone explain this moment?


Solution

  • // 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
    

    To do what you want use concatenation like this

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

    If you really want all the spaces

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

    Or maybe

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