I wrote a function for my coursework that will receive a string, a starting number and a length. The function will take the string and output the string that’s created by taking all the letters including and after string{n}
for example:
string = kingsbridge, n = 4, l = 4.
string created = gsbr.
The first two validation parts of the function work fine, but when it actually comes to creating the substring to be output the following occurs:
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
…and so on and so on (infinite loop)
here’s my code:
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";
}
}
}
Any help as to why this is happening (or why it’s created an infinite loop) would be appreciated!
Thank you 🙂
edit: I know that in the example i gave string{4} would be s, but the user inputs the number, so I will minus 1 to get the letter they need
Your
forloop is a mess, pure and simple. Take a good look at it (first clearing the infinite loop issue):So, you’re setting $letter to be $n-1, and I assume that you want to loop over all the letters. Then, your loop condition is “if $l”. You’re not changing the value of $l at all in the for loop, so how could you expect the program to break out of it?
If you’re trying to loop over all the letters, as it stands, you’re better off doing
$letter = $n-1; $letter >= 0; $letter--.Finally, I need the content of
$sto be able to debug the other issue. Edit your question!