Search code examples
phpwhile-loopcomparison

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?


Solution

  • $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;
    }