我为我的课程作业编写了一个函数,它将接收一个字符串、一个起始数字和一个长度。该函数将获取字符串并输出通过获取所有字母(包括和之后)创建的字符串string{n}
例如:
string = kingsbridge, n = 4, l = 4.
string created = gsbr.
该函数的前两个验证部分工作正常,但是当实际创建要输出的子字符串时,会发生以下情况:
Notice: Uninitialized string offset: 11 in G:\xampp\htdocs\say\ws21C.php on line 58
Notice: Uninitialized string offset: 12 in G:\xampp\htdocs\say\ws21C.php on line 58
Notice: Uninitialized string offset: 13 in G:\xampp\htdocs\say\ws21C.php on line 58
Notice: Uninitialized string offset: 14 in G:\xampp\htdocs\say\ws21C.php on line 58
...等等等等(无限循环)
这是我的代码:
function substring($s, $n, $l){
$substring = "";
if($n > length($s)){ //If asking for substring that starts with an index of the string that's greater than the actual length
echo "Out of range";
}
else{
if($l > (length($s) - ($n - 1))) { //If start is in index of string but length would mean substring would trail off string
$newLength = ((length($s)) - ($n - 1));
substring($s, $n, $newLength);
}
else{ //PROBLEM CODE
for($letter = ($n - 1); $l; $letter++){
$substring .= $s{$letter}; //Line 58
}
echo "$substring";
}
}
}
任何有关为什么会发生这种情况(或为什么会创建无限循环)的帮助将不胜感激!
谢谢 :)
编辑:我知道在示例中我给出的字符串 {4} 将是 s,但用户输入了数字,所以我将减去 1 以获得他们需要的字母