Setting an array based on result if one record/field is different

I’m not sure of the terminology for what I’m asking for!
I have a table with multiple entries which I have a select query getting the records I require. If any of the records have Yes in one of the fields I need to echo “Yes”. Most of the records will have a no, in which case I need to echo “No”.
I’m trying to amend old code without having to re-write the entire site so if anyone can help that would be great.

             $query2  = "SELECT * FROM ProductCodes 
             INNER JOIN IngredientsList ON ProductCodes.id = IngredientsList.BACode 
             WHERE ProductCodes.id = '$IngredientBACode'";
             $result2 = mysql_query($query2);


          while($row = mysql_fetch_array($result2)) {
               $COO = $row['COO'];

               $item_name3 = $row['item_name'];
               $Allergen = $row['Allergen'];
	   $i = $row['FreeFromArtificialColours'];
            
            
							if($Allergen === 'Yes'){
									echo "<b>$item_name3,&nbsp;</b>";
							}else{
									echo "$item_name3,&nbsp;";
            
            

              }
           }

If $i = $row[‘FreeFromArtificialColours’]; is Yes for any of the records I need to display ‘Yes’

1 Like

before the loop: $found = false;

within the loop: if($i == 'Yes') $found = true;

after the loop: if($found) echo 'Yes';

1 Like

I think there’s a couple of ways to read this - the solution from @chorn above will do exactly as you say you want - if any of the records contains “Yes” in the “Freefrom…” column then it will display “Yes” at the bottom of the list.

But, do you want to display a single “yes” to show that one of the names in the list has that status, or do you want to display the “Yes” alongside the item name, to indicate which specific item names have that status? If this is what you want, then simply modify this bit of code:

if ($i == "Yes") $dispFree = "Yes" else $dispFree = "No";
if($Allergen === 'Yes'){
  echo "<b>$item_name3 $dispFree,&nbsp;</b>";
  }else{
  echo "$item_name3 $dispFree,&nbsp;";
  }

to add the first line, then just display $dispFree wherever you want it to be. Obviously you can change the value for “No” to be blank, or whatever.

I need the result to stay as No even if the following record in the loop is Yes.
e.g.
table1
id | FreeFromArtificialColours
1 | Yes
2 | Yes
3 | No
4 | Yes

The result should then be No as 1 of the records is No even though there are records after this.
From what I understand your solution is setting a variable and basing the result on the last record in the loop.

just switch the comparison to == 'NO', so that any NO is found

No, that’s not the case - that solution will set the value to “Yes” and leave it that way, if any record found in the loop contains “Yes”.

Some clarification might be good - earlier you wanted the result to be “Yes”.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.