因为字符串没有那么多索引!该指数从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
它应该是'$ i <$ getl'而不是'$ i <= $ getl'。 – honk
字符串中的'L'表示索引0,字符'4'表示索引2,但for循环上升到索引3。 – Eric