samedi 6 avril 2019

Dynamically create PHP if condition

I have a form with multiple fields a user can search by. How do I dynamically write the if condition based on the fields selected by user?

E.g. I have 3 fields as follows:

$categoryId = $_REQUEST['category_id'];
$locationId = $_REQUEST['location_id'];
$statusId = $_REQUEST['status_id'];

If the user selected category_id and location_id and status_id then my if statement would be should be as follows:

if (!empty($categoryId) && !empty($locationId) && !empty($statusId)) {
  if (isInTaxonomy($recordId, $categoryId) && isInTaxonomy($recordId, $locationId) && isInTaxonomy($recordId, $statusId) {
    // Do something
  }
}

if the user selected category_id and location_id then my if statmeent would be as follows:

if (!empty($categoryId) && !empty($locationId)) {
  if (isInTaxonomy($recordId, $categoryId) && isInTaxonomy($recordId, $locationId) {
    // Do something
  }
}

As you can see I'm having to implement every possible combination of fields a user can select to build all the different conditions.

Is there a way to dynamically generate all the condition using more concise code without having to resort to Eval?

Aucun commentaire:

Enregistrer un commentaire