0

I'm trying to figure out how to count the loops in this foreach loop. I don't want to count the combined # of items. I just want a to count how many times it loops through.

I've tried the following outside of the loop, but I get a "0".

$result = count($row); 
echo "$studentEmail | Recipe Count = $result";

I've also tried it inside of the loop, but it doesn't work either.

$sql is created with the following. It is a collection of 11 fields organized into a form submission.

$sql = "SELECT * FROM recipes where email = '$studentEmail'";

Ideas?

    foreach ($pdo->query($sql) as $row) { 
            echo '<tr>'; echo '<td>'. $row[1] . '</td>'; 
            echo '<td>'. $row['name'] . '</td>'; 
            echo '<td>'. $row['description'] . '</td>'; 
            echo '<td>'. $row['steps'] . '</td>'; 
            echo '<td>'. $row['ingredientsMain'] . '</td>'; 
            $timePrep = unserialize($row['timePrep']); 

            echo '<td>'. $timePrep[0] . ' minutes, '. $timePrep[1] . ' hours</td>'; 
            $timeCook = unserialize($row['timeCook']); 

            echo '<td>'. $timeCook[0] . ' minutes, '. $timeCook[1] . ' hours</td>'; 
            echo '<td>'. $row['ingredientsAll'] . '</td>'; 
            echo '<td>'. $row['difficulty'] . '</td>'; 
            echo '<td>'. $row['mealDiet'] . '</td>'; 
            echo '<td>'. $row['mealTypeCourse'] . '</td>'; 
            echo '<td>'. $row['photos'] . '</td>'; 
            echo '<td><a class="btn" href="read.php?id='.$row['id'].'">Read</a></td>'; echo '</tr>'; }

Thank you!

Mr. B
  • 2,677
  • 6
  • 32
  • 42

1 Answers1

2

You can simply increment a variable during the loop.

$result = 0;
foreach ($pdo->query($sql) as $row) {
    // all your echo statements
    $result++;
}
echo "$studentEmail | Recipe Count = $result";
Barmar
  • 741,623
  • 53
  • 500
  • 612