Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a if statement inside a while loop

Tags:

php

I have a while loop that returns X amount of data with the same value X amount of times before it changes to a different value.

// example 121, 121, 121, 121, 113, 113, 113, 113 

each value is on its own line so a while loops puts them on the next is it possible to have an if that uses when the value changes ?

some thing like

while($row = $result->fetch_assoc()) {

    if ($row["name"] == $row["name"]){
         echo "<tr><td>".$row["name"]."</td><td>".$row["combi"]."</td>"
    }else{
         echo "<td>".$row["combi"]."</td></tr>"
    }
}
like image 271
Niall Collier Avatar asked Nov 24 '25 18:11

Niall Collier


1 Answers

You just use another variable to stock the last value

<?php
$lastval = 0;
while($row = $result->fetch_assoc()) {

    if ($row["name"] != $lastval){
        $lastval = $row["name"];
        // value has changed
    }else{
        // Value is the same as the last one
    }
}
?>

Don't forget to "ORDER BY name"

like image 131
Fadhel Bey Avatar answered Nov 26 '25 12:11

Fadhel Bey