【问题标题】:What happened with length variable in this example, PHP在这个例子中,长度变量发生了什么,PHP
【发布时间】:2016-10-04 22:27:46
【问题描述】:

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

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

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

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

谁能解释一下这一刻?

【问题讨论】:

    标签: php variables string-length


    【解决方案1】:
    // 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');
    

    【讨论】:

    • 感谢您的快速答复。你能说出为什么它只会添加一个字母 D,为什么不添加整个“Doe”?))
    • 它只能添加“D”,因为您只加载 1 次出现,即 [10],即 $text[10] 中只有空间用于 Doe 的第一个字符
    【解决方案2】:

    字符串可以作为数组访问,这就是您使用 $text[10] 所做的。由于内部工作原理,$text[10] = 'Doe'; 所做的所有事情都是将第 11 个字符设置为“D”。

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

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

    【讨论】:

      【解决方案3】:

      可用数据

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

      解决方案的概念

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

      要理解这一点,只需运行:

      echo $text[0]

      在您的浏览器中,您会注意到输出是 "J"

      运行

      同样如果你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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-13
        • 2020-03-13
        • 2013-09-14
        相关资源
        最近更新 更多