Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a value with previous row in a while loop?

Tags:

php

I'm a newbie in PHP, so forgive me for a basic question.

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?

like image 305
dutraveller Avatar asked Apr 11 '09 09:04

dutraveller


2 Answers

Just store it:

$get = mysql_query("...");
$previous = '';
while ($row = mysql_fetch_assoc($get)) {
  $current = $row['...'];
  if ($current == $previous) {
    // do stuff
  }
  $previous = $current;
}
like image 117
cletus Avatar answered Nov 15 '22 06:11

cletus


$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;
}
like image 9
Terry Avatar answered Nov 15 '22 08:11

Terry