Reputation: 887
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!
Upvotes: 2
Views: 1987
Reputation: 745
You may use foreach and array_reverse to get the array values:
foreach(array_reverse($words_length) as $val){
echo $val;
}
Upvotes: 1
Reputation: 5141
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));
Upvotes: 2
Reputation: 32701
If you simply want to have the output in reverse order use array_reverse
:
print_r(array_reverse($words_length));
Upvotes: 3
Reputation: 24710
The quickest fix is to add print_r(array_reverse($words_length));
after the loop
Upvotes: 2