Reputation: 5445
I'm trying to create somewhat of a fuzzy search with PHP. Consider the following pseudo code/scenario below.
Take these $_POST
ed values:
name
price
location
age
And I have an array of items (lets assume cars), of which each item contains the following properties:
name
price
location
age
So in my function, I use an if()
within a foreach()
to check if any of the posted data matches with an item and if it does, echo the item.
function search() {
$items = array(...);
$name = $_POST['name'];
$price = $_POST['price'];
$location = $_POST['location'];
$age = $_POST['age'];
foreach($items as $item) {
if(
$item['name'] == $name &&
$item['price'] == $price &&
$item['location'] == $location &&
$item['age'] == $age
){
echo json_encode($item);
}
}
}
The issue is that not every posted value is filled in, so for example $name
could be empty i.e. $name = ''
.
Question: How can I exclude any of the items in the if()
statement if the initial $_post
ed key is empty without creating an if()
inception type scenario? I considered using ||
but I'm pretty sure that wouldn't be the same as excluding a comparison all together. A
Upvotes: 1
Views: 430
Reputation: 463
You can achieve that by taking advantage of PHP's lazy interpreter:
if(
(!$name || ($name && $item['name'] == $name)) &&
(!$price || ($price && $item['price'] == $price)) &&
(!$location || ($location && $item['location'] == $location)) &&
(!$age || ($age && $item['age'] == $age))
){
echo json_encode($item);
}
This will first check that each variable is not null, nor empty. (How exactly does if($variable) work?) Also look at Does PHP have short-circuit evaluation?
Upvotes: 2