• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 280
  • Last Modified:

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...
}
0
sbayrak
Asked:
sbayrak
1 Solution
 
Daniel WilsonCommented:
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

0
 
Terry WoodsIT GuruCommented:
$query = "SELECT count(distinct field_qty_item) FROM ...";

if result == 1 then
  #they are all the same
else
 #they're not
0
 
Chris StanyonCommented:
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.
0
 
sbayrakAuthor Commented:
smooth
0

Featured Post

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

Tackle projects and never again get stuck behind a technical roadblock.
Join Now