How to handle multiple if statements PHP

86 Views Asked by At
  • List item

just wanted some opinions on the most efficient way to do this. I have an email input and a phone input. I have JQuery validation applied which works well. Basically, they both can't be empty. If only one is provided, that is fine. If both are provided, thats fine too.

Each field will call its own API. If the phone field is provided, it will call a phone API, if the email field is provided it will call and email API, if both fields are provided, it will call both APIs. To handle this, I pretty much do

if (isset($_POST["email"]) && !empty($_POST["email"])){
    //call email API
}
if (isset($_POST["phone"]) && !empty($_POST["phone"])){
    //call phone API
}

This seems to cover all the cases above, although there may be a more efficient way to do this.

With my validation, I also want to record any time the submit button is pressed (it will fail validation and user wont know, I just want it recorded). So I have a invalidHandler set up and I grab the values of the inputs (if any) and pass them to PHP.

What would be the best way to handle this in PHP though? I dont want it firing if only one field is filled in because the above will handle that. I also dont want it firing if both fields are empty. I only really want it firing if one or both fields have invalid data (failed validation). If one field has valid data and another one does not, then I dont need to worry about this.

So really just looking for the best way to handle something like this in PHP.

Thanks

2

There are 2 best solutions below

2
On BEST ANSWER

Not sure what you're really asking, but I think what you need is a flag for each check, and an OR opreator:

$flag_phone = $flag_email = false;
if (phone_has_invalid_data()) {
    $flag_phone = true;
}
if (email_has_invalid_data()) {
    $flag_email = true;
}
if ($flag_email OR $flag_phone) {
    //throw some error
} else {
    //everything ok
}

(and speaking of unnecessary optimizations, the code if (isset($var) && !empty($var)) is equivalent to if (!empty($var)))

0
On

It's a reasonably pointless optimisation, but you can do this:

if (isset($_POST["email"]) && !empty($_POST["email"])){
    //call email API
} elseif (isset($_POST["phone"]) && !empty($_POST["phone"])){
    //call phone API
}

Other than that, it looks fine