2
<?php

$a = "Hello World I am Neha Singh Chouhan";
$length = 0;  
do {
    $length++; 
}
while ($a[$length] != null);
echo "Length = ".$length."<br/>";
for ($i = $length - 1; $i >= 0; $i--) {
    echo $a[$i]; 
}

?>

tried to calculate the string length without using inbuilt function strlen().

the output was

Notice: Uninitialized string offset: 35 in C:\xampp\htdocs\Neha\ProgramsFromClass\10_reverse_string.php on line 7
Length = 35 nahuohC hgniS aheN ma I dlroW olleH

What causes the notice and how can i get rid of it?

MC Emperor
  • 22,334
  • 15
  • 80
  • 130

1 Answers1

0

Your loop is incorrect. You increment your $length BEFORE you start using it, and run off the end of the string. Therefore you're testing offsets, 1,2,3,...n, where n is one past the end of the string.

And since you're testing for a non-existent "array" key, no matter how you look at it, you'll always get the error, even after you swap the loop types.

do/while is NOT the loop to use for this. You want a plain while loop, and use isset() instead:

$length = 0;
while(isset($a[$length])) { $length++; }
Marc B
  • 356,200
  • 43
  • 426
  • 500