user849137
user849137

Reputation:

trying to save time with PHP if/elseif statements

I have a rather big if statement:

if (!$result_spam)
{
$confrim_spam = "FAILED";

}
else if ($result_spam)
{
$confrim_spam = "PASSED";
}

if (!$result_email_manage)
{
$confrim_email_manage = "FAILED";

}
else if ($result_email_manage)
{
$confrim_email_manage = "PASSED";
}

if (!$result_analyt)
{
$confrim_analytics = "FAILED";
}

else if ($result_analyt)
{
$confrim_analytics = "PASSED";
}

Now I want to do another if statement to check if all have PASSED or if all have FAILED or is some have PASSED and some have FAILED and then echo (do something with) the failed ones.

I know how to check if all have passed or failed:

if ($confirm_spam == "PASSED" AND $confirm_analytics == "PASSED"

but to check if some have passed and some haven't and then find the ones that failed will take too long, right?

I was just wondering, would there be an easier/quicker way to do this?

Upvotes: 0

Views: 60

Answers (3)

user898741
user898741

Reputation:

What if you try this way:

$passed = $failed = "";

$all = array("confrim_spam" => $result_spam,
             "confrim_email_manage" => $result_email_manage,
             "confrim_analytics" => $result_analyt);


foreach($all as $a => $b)
{
    if (!$b)
        $failed.= $a . ", ";
    else
        $passed.= $a . ", ";
}

Then if var $passed is empty, none passed else if $failed is not empty, at last one have not passed.. so do you got what passed and what failed and do something with them. And you can store results both in a string or an array whatever you want...

Upvotes: 1

Naftali
Naftali

Reputation: 146300

Since they are all bools anyway:

if($result_spam && $result_email_manage && $result_analyt){
    //do all passed
}
elseif($result_spam || $result_email_manage || $result_analyt){
   //at least one passed
   if(!$result_spam){ echo '$result_spam failed';}
   if(!$result_email_manage){ echo '$result_email_manage failed';}
   if(!$result_analyt){ echo '$result_analyt failed';}
}
else {
   //do all failed
}

Upvotes: 2

a1ex07
a1ex07

Reputation: 37364

You can change validation logic to something like

$passed = array();
$failed = array();
if (!$result_spam)
{
   array_push($failed, "confirm_spam");
}
else
{
   array_push($passed, "confirm_spam");
}
...

Then you have an easy and clear way to check whether all passed/failed and which tests are failed.

Upvotes: 1

Related Questions