0

I have created a for loop. I am trying to loop through lots of members and create a row for each member in a table.

It's looping through too many times. Is it the right type of loop to use?

        <?php
    for ($i = 1; $i = count($u); $i++) 
    {
        ?>
        <tr>
                <?php
                    echo "<td>$i</td>";
                ?>

                <?php
                foreach ($u as $username)
                {
                    echo "<td>$username</td>";
                }
                ?>
                <?php
                foreach ($p as $points)
                {
                    echo "<td>$points</td>";
                }
                ?>
        </tr>
        <?
    }
    ?>

$u and $p are arrays.

Thanks

sark9012
  • 5,485
  • 18
  • 61
  • 99

3 Answers3

4

You can shorten it a bit and remove the inner loops:

<php
 for ($i = 1; $i <= count($u); $i++) 
 {
   echo '<tr>';
   echo "<td>$i</td>";
   echo "<td>$u[$i]</td>";
   echo "<td>$p[$i]</td>";
   echo '</tr>';
 }
 ?>
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

$i = count($u) in the loop is what's causing the problem:

for ($i = 1; $i = count($u); $i++)

On every iteration of the loop, you're assigning count($u) to $i using a single =. Should be

for ($i = 1; $i <= count($u); $i++)

or

for ($i = 0; $i < count($u); $i++)
Andy E
  • 338,112
  • 86
  • 474
  • 445
0
<?php
$count = count($u);
for ($i = 1; $i < $count; $i++) {
    echo '<tr>';
    echo '<td>' . $i . '</td>';
    foreach ($u as $username) {
        echo '<td>' . $username . '</td>';
    }
    foreach ($p as $points) {
        echo '<td>' . $points . '</td>';
    }
    echo '</tr>';
}
?>

You should count $u before you loop it.

Tech163
  • 44
  • 1
  • 2