Inventor
Inventor

Reputation: 505

is there a way to compare multiple values in php

My code below is sending me the email even if this statement isn't true if($value['flagS']=='Yes'& $value['flagE']=='Yes' & $value['flagL']=='Yes' & $value['flagML']=='Yes') see my code below and assist, where am i going wrong

  $flagquery = "SELECT * FROM approved"; 

        try 
        { 

        $stt = $db->prepare($flagquery); 
        $stt->execute(); 
        } 
        catch(PDOException $ex) 
        { 

        die("Failed to run query: " . $ex->getMessage()); 
        } 


        $rows = $stt->fetchAll(); 

        foreach($rows as $value):

        if($value['flagS']=='Yes'& $value['flagE']=='Yes' & $value['flagL']=='Done' & $value['flagML']=='Done'){


        $message = "your request was approved <br/>                     
                                            <br /><br />";

        $subject = "Application $identifier has been approved ";

        $email="[email protected]";


        send_mail($email,$message,$subject);


Blockquote

Upvotes: 0

Views: 182

Answers (4)

Thomas Abplanalp
Thomas Abplanalp

Reputation: 1

I used to design flags with bit operations.

define("flagS", 1);
define("flagE", 2);
define("flagL", 4);
define("flagML", 8);
define("allFlags", 15); // join all flags (flagS | flagE | flagL | flagML)

It needs less space in db and you can check the flags very easy without expensive loops.
If a single flag is set, use

if($storedFlags & flagS) {
    //Flag flagS is set
} else {
    // Flag is not set
}

If more than one is set, use

$required = flagE | flagML;
if( ($storedFlags & $required) == $required) {
    // Flags flagE and flagML are set
} else {
    // No or only one flag is set
}

To check if all are set, simply replace $required with allFlags or 15, if the count of flags does not change.

Upvotes: 0

Mohit Shukla
Mohit Shukla

Reputation: 65

you should use && in if condition

AND operation:

& -> will do the bitwise AND operation , it just doing operation based on the bit values. && -> It will do logical AND operation. It is just the check the values is true or false. Based on the boolean value , it will evaluation the expression

Upvotes: 0

Naincy
Naincy

Reputation: 2943

To write it in more optimised way.

$keys_to_match = ['flagS', 'flagE', 'flagL', 'flagML'];
foreach($rows as  $key => $value) {

   if(in_array($key , $keys_to_match) && $value[$key] ==='Yes') {

     // ....
   }
}

Upvotes: 0

dbrumann
dbrumann

Reputation: 17166

Please be careful, I don't think your condition does what it's supposed to do. Using a single & is a bitwise operator when you probably want &&, i.e. a logical operator.

if($value['flagS'] == 'Yes'
   && $value['flagE'] == 'Yes'
   && $value['flagL'] == 'Yes'
   && $value['flagML'] == 'Yes'
) { ... }

This will now check all 4 flag values (S, E, L, ML) for "Yes" and only then return true.

Upvotes: 1

Related Questions