为什么此函数会生成未初始化的字符串偏移通知?

I'm having this error when I run my program:

Notice: Uninitialized string offset: 7 in C:\xampp\htdocs\demo\str_rev.php on line 21

What causes that?

<?php

    //strrev($arg);
    /*$str = "ademola";
    echo strrev("$str");
    */

    function reverse_String($str){
        $i = 0;
        while(!empty($str[$i])){
            echo $str[$i];
                $i++;
        }


        for($r = $i; $r > -1; $r--){
            $reverse = $str[$r];
            echo $reverse;

        }
    }

    reverse_String("Ademola");
?>

Output:

Ademola
Notice: Uninitialized string offset: 7 in C:\xampp\htdocs\demo\str_rev.php on line 21
alomedA

The $i++; in your first while loop increments $i to 7 in its last iteration. The condition !empty($str[$i]) is no longer satisfied, so the loop does not execute again, but $i is still 7 when the next loop starts, which is an index beyond the end of the string.

There are various ways to fix this, a simple way is to subtract 1 from the counter when you define your second loop to set $r to the index of the last character in the string.

for($r = $i - 1; $r > -1; $r--){ ...

As mentioned by Don't Panic there are many ways to fix this, you can use isset as:-

    for($r = $i; $r > -1; $r--){
        if(isset($str[$r])) {
            $reverse = $str[$r];
            echo $reverse;
        }
    }

Or to reverse the string you can simply use the php's built in function (strrev)

echo strrev('Ademola')