Link to home
Start Free TrialLog in
Avatar of sbayrak
sbayrakFlag for Türkiye

asked on

if all rows found are equal to each other

How can we use if statement inside the foreach loop below to check whether all the row values (no matter what their count is) returned by the mysql query are equal to each other?

$query = "SELECT field_qty_item FROM ...";
foreach ($query as $row) {

   if all $row values returned are equal to each other...
   // do smthng
   
}
else {
// do nothing... or do another thing...
}
Avatar of Daniel Wilson
Daniel Wilson
Flag of United States of America image

There are many ways ... but this should work.
$FirstValSet = false;
$FoundMismatch = false;

$query = "SELECT field_qty_item FROM ...";
foreach ($query as $row) {
   if (!$FirstValSet){
    $val = $row[0];
    $FirstValSet = true;
  }else{
    if ($row[0] != $val){
      $FoundMismatch=true;
      break;
    }
  }
}
   if all $row values returned are equal to each other...
if (!$FoundMismatch){
   // do smthng
   
}
else {
// do nothing... or do another thing...
} 

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What exactly are you trying to achieve. Maybe the IF statement isn't the best way forward.

You can have a GROUP BY clause in your SQL Statement:

SELECT count(field_qty_item) as Amount, field_qty_item FROM yourTable GROUP BY field_qty_item

Open in new window

You would then only get unique values of field_qty_item, along with an Amount of how many times each value exists in the database. If you only get 1 record returned then clearly all the rows match each other.
Avatar of sbayrak

ASKER

smooth