There is a script:

$number = "123"; $sum = 0; for($i = 0; $i <= strlen($number); $i++) { $sum += $number[$i]; } echo $sum; 

When executed, it produces a notice error:

ununitialize string offset on line 4.

I can not understand why?

  • 3
    Replace <= with < because the pointer goes out of line. - Visman
  • Thank! Worked) - Beginner

1 answer 1

You have 3 characters in a line ( strlen($number) returns this value), and since counting starts from zero, then they have indices 0,1,2, respectively.

In the for clause, you start from zero, and the condition <= says that you need to iterate over all characters with indices from 0 to 3, including index 3 itself, which, as written above, does not. As soon as you try to access the symbol at index 3 you get an error.

You must either change the condition or reduce the number of characters:

for($i = 0; $i < strlen($number); $i++) {

for($i = 0; $i <= strlen($number)-1; $i++) {