user1242749
user1242749

Reputation: 119

Looping issue PHP

Here is the code:

$TopFive = array_slice($counts,0,5);    
{
  foreach($TopFive as $key => $tops)
{


for($i=0; $i<$tops; $i++)
{
  echo "*";
}

$b=0;   
for($a=0; $a<5; $a++)
{
  $b++; 
}

echo "{$b}";        
echo "#:{$key} - {$tops} <br/>";    


                }
            }

currently, the output looks this:

*********5#:THE - 9 
*****5#:OF - 5 
*****5#:TO - 5 
***5#:AND - 3 
***5#:THEM - 3 

but what I really want to have is this:

********* #1: THE - 9
***** #2: OF - 5
***** #3: TO - 5
*** #4: AND - 3
*** #5: THEM - 3

I can't seem to figure out how to arrange the looping. Any ideas? I am very sorry this simple question, I ran out of ideas. I just want the numbers to be from 1-5.

I just want some advice as to how to arrange the looping for the $b so that the counting will be from 1-5, not just 5

Upvotes: 1

Views: 65

Answers (4)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

In your code, please change this part:

echo "{$b}";        
echo "#:{$key} - {$tops} <br/>";    

To:

// echo "{$b}";        
echo "#$i:{$key} - {$tops} <br/>";

And use str_repeat('*', $count) instead of a for loop! :)

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53525

You can change your code to:

$b=1;
foreach($TopFive as $key => $tops)
{                                   
    for($i=0; $i<$tops; $i++)
    {
        echo "*";
    }          
    echo "#$b:{$key} - {$tops} <br/>";    
    $b++;
 }

but all the inner loops are redundant.

Upvotes: 0

cmbuckley
cmbuckley

Reputation: 42458

If:

$TopFive = array('THE' => 9, 'OF' => 5, 'TO' => 5, 'AND' => 3, 'THEM' => 3);

then:

$number = 1;

foreach ($TopFive as $word => $count)
{
    echo str_repeat('*', $count); // Outputs '*' characters
    echo " #{$number}: {$word} - {$count}\n";
    $number++; // increment your number
}

Here's an example.

Upvotes: 3

Vinayak Garg
Vinayak Garg

Reputation: 6616

Your this line has problem for($a=0; $a<5; $a++)

$b always increments to 5

To solve this, just initialize $x (or anything) outside foreach loop with 1. Do away with $b and simply echo $x; $x++; at appropriate place.

Upvotes: 0

Related Questions