2014-12-20 35 views
0

代码工作正常,但即时得到下面的错误:PHP错误在循环

Notice: Uninitialized string offset: 3 in /Applications/XAMPP/xamppfiles/htdocs/kwame.php on line 8

有人可以解释为什么会这样。谢谢。

<? 

$string ='Lt4'; 
$getl = strlen($string); 

for($i=0; $i<=$getl; $i++){ 

echo $string[$i]; 
} 

?> 
+2

它应该是'$ i <$ getl'而不是'$ i <= $ getl'。 – honk

+0

字符串中的'L'表示索引0,字符'4'表示索引2,但for循环上升到索引3。 – Eric

回答

3

因为字符串没有那么多索引!该指数从0开始只是改变<=<像这样:

<?php 

    $string = "Lt4"; 
      //^^^-Index 2 
      //||-Index 1 
      //|-Index 0 

    $getl = strlen($string); //Length: 3 

    for($i = 0; $i < $getl; $i++) { //i -> 0, 1, 2 
     echo $string[$i]; //L, t, 4    
    } 

?> 

迭代概述:

    Variables   Condition     Output 

       | $i | $getl | $i < $getl = ?  | $string[$i] 
----------------------------------------------------------------------------- 
Start:  | 0 | 3  |  
Iteration 1: | 0 | 3  |  0 < 3  = TRUE |   L (Index 0) 
Iteration 2: | 1 | 3  |  1 < 3  = TRUE |   t (Index 1) 
Iteration 3: | 2 | 3  |  2 < 3  = TRUE |   4 (Index 2) 
Iteration 4: | 3 | 3  |  3 < 3  = FALSE |  [OFFSET] 
       |  |   |      | 
End   | 3 | 3  |      | 
       |  |   |      | 

输出:

Lt4 
1
<?php 
$string ='Lt4'; 
$getl = strlen($string); 
for($i=0; $i<$getl; $i++){ 
echo $string[$i]; 
} 
?> 

enter image description here

索引始终从0开始