Tina Turner
Tina Turner

Reputation: 91

For loop inside Foreach

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.

Upvotes: 2

Views: 15239

Answers (4)

Pupil
Pupil

Reputation: 23948

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
}
?>

Upvotes: 7

Nirnae
Nirnae

Reputation: 1345

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>';
?>

Upvotes: 2

Chin Lee
Chin Lee

Reputation: 133

Try to use the key in foreach

<?php foreach ($users as $key => $user) : ?>
<tr>
    <td><?php echo $key; ?></td>
    <td><?php echo $user['firstname']; ?></td>
</tr>
<?php endforeach; ?>

Upvotes: -1

Niroj Adhikary
Niroj Adhikary

Reputation: 1835

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

Upvotes: 0

Related Questions