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
}
}
if the user only selected category_id then my if statmeent would be as follows:
if (!empty($categoryId)) {
if (isInTaxonomy($recordId, $categoryId)) {
// 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.
I was thinking of doing something like the following but that just give me a string and I don't want to use eval to execute it:
$filter = [(!empty($categoryId) ? '(isInTaxonomy($recordId, $categoryId))' : ''),
(!empty($locationId) ? '(isInTaxonomy($recordId, $locationId))' : '')];
$condition = implode(' && ', array_filter($filter));
if (eval("return $condition;")) {
// Do something
}
Is there a way to dynamically generate all the condition using more concise code without having to resort to Eval?