如何在while循环中订购?

I want to get the count of characters from the following words in the string. For example, if my input is I am John then the output must be like this:

9 // count of 'I am John'
4 // count of 'I am'
1 // count of 'I'

I use the code like this in PHP for this process:

$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);

$i =0;
while ($i<$count_words){
    if($i==0) {
    $words_length[$i] = strlen($words[$i]);
    } else {
    $words_length[$i] = strlen($words[$i])+1+$words_length[$i-1];
    }
    echo $words_length[$i]."<br>";
    $i++;
}

But it return the output like this:

1
4
9

Why ? Where is my error ? How can I change the ordering ?
What does my code must be like ?
Thanks in advance!

If you simply want to have the output in reverse order use array_reverse:

print_r(array_reverse($words_length));

The quickest fix is to add print_r(array_reverse($words_length)); after the loop

Your problem is that you're looping through the words left to right. You can't output the full length right to left, because each one depends on the words to it's left.

You could take the echo out of the loop, and print the values after all have been calculated.

$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);

$i =0;
while ($i<$count_words){
    if($i==0) {
        $words_length[$i] = strlen($words[$i]);
    } else {
        $words_length[$i] = strlen($words[$i])+1+$words_length[$i-1];
    }
    $i++;
}

print implode('<br />', array_reverse($words_length));

You may use foreach and array_reverse to get the array values:

foreach(array_reverse($words_length) as $val){
echo $val;
}