For loop inside Foreach

10,732

Solution 1

If you want unique index number for user, you do not need extra loop.

Just add an increment variable:

And increment it in existing loop.

<?php
$i=0;
foreach($users as $user) {
  ++$i; // For printing first user, it will be 1 not 0. 
  // Therefore, increment is placed before printing name.
?>
  <tr>
    <td><?php echo $i;?></td>
    <td><?php echo $user['firstname']; ?></td>
  </tr>
<?php
}
?>

Solution 2

This should be enough to achieve what you're trying to do :

Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it.

Also you should avoid to open your php tags ten thousands times for a better visibility into your code :)

<?php
        $i = 0;
        foreach($users as $user) {
            $i++;
            echo'<tr>
                    <td>'.$i.'</td>
                    <td>'.$user['firstname'].'</td>
                </tr>';
?>
Share:
10,732
Tina Turner
Author by

Tina Turner

Updated on June 15, 2022

Comments

  • Tina Turner
    Tina Turner almost 2 years

    I got a foreach which loops through my database for each user.

        <?php
            foreach($users as $user) {
        ?>
            <tr>
                <td>
                    <?php
                    for ($i=1; $i < 52; $i++) {
                        echo $i;
                    }
                    ?>
                </td>
                <td>
                    <?php echo $user['firstname']; ?>
                </td>
             </tr>
    <?php
    }
    ?>
    

    This loop through database and echos the username, now I tried to build a for loop inside this so that every user has a number, I took as an example a very basic for loop ( it will be changed later). The problem is that I get all numbers printed out for each user, but I just want to print out the number once for a user. How do I solve this.