dutraveller
dutraveller

Reputation: 327

Comparing a value with previous row in a while loop?

In a while() statement, is there a way to know if a value in a row is equal to a value in the previous row?

Upvotes: 7

Views: 14074

Answers (2)

Terry
Terry

Reputation: 110

$get = mysql_query("...");
$previous = '';
while ($row = mysql_fetch_assoc($get)) {
  $current = $row['...'];
  if ($current == $previous) {
  // do stuff
}
$previous = $current;
}

This example won't work correctly. It will always skip the first record in the array. The first time through $previous will be blank so $current and $previous won't be equal. $current will have to blank the first pass, just as previous. $current will have to be made equal inside the if loop.

$get = mysql_query("...");
$previous = '';
$current = '';
while ($row = mysql_fetch_assoc($get)) {

  if ($current == $previous) {
     $current = $row['...'];
    // do stuff
   }
 $previous = $current;
}

Upvotes: 9

cletus
cletus

Reputation: 625327

Just store it:

$get = mysql_query("...");
$previous = '';
while ($row = mysql_fetch_assoc($get)) {
  $current = $row['...'];
  if ($current == $previous) {
    // do stuff
  }
  $previous = $current;
}

Upvotes: 20

Related Questions