How to exclude a parameter within an if statement? - php

I'm trying to create somewhat of a fuzzy search with PHP. Consider the following pseudo code/scenario below.
Take these $_POSTed 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 $_posted 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

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?

Related

How to Apply If Statement for both Capital & Small Letters

I want to add one If Statement in my script. If it gets any of the name mentioned, it converts it to admin. If script gets name like arsh, then it convert it to admin. But if script gets name like ARSH, Arsh, arSh, arsH then It should also convert it to admin... I can't manually define each work manually. So looking for a good way to get this work done.
if ($name=='arsh' || $name=='saif' || $name=='john' || $name=='smith'){
$name = 'Admin';
}
convert capital or small letters name to admin
You may compare the lowercase input name against lowercase literals:
$lname = strtolower($name);
if ($lname == 'arsh' || $lname == 'saif' || $lname == 'john' || $lname == 'smith') {
$name = 'Admin';
}
You can use strcasecmp() which doesn't require changing the case or mutating your variable:
if (strcasecmp($name, 'arsh') === 0 || strcasecmp($name, 'saif') === 0 || strcasecmp($name, 'john') === 0 || strcasecmp($name, 'smith') === 0){
$name = 'Admin';
}
Or just convert the names to either upper or lowercase before you do your comparison. Just make sure you assign it to another variable if you need to have the original value unaltered.
$name = strtolower($name);
if ($name=='arsh' || $name=='saif' || $name=='john' || $name=='smith'){
$name = 'Admin';
}

Using empty() to adjust output with multiple variables

I have two primary variables that are composed of strings and other variables. I want the two primary variables only to be echo'ed if all the variables that they are comprised of have data.
The two primary variables are $introduction and colortxt.
$introduction is comprised of $finalvehicle3, $bodystyle, $mileage, and $hi.
$colortxt is comprised of $model, $exterior, and $interiorspec.
If any of the secondary variables are empty, I don't want the primary variable to be displayed.
Below is the code I have created that doesn't seem to be working. I have been using empty().
My PHP:
<?php
$finalvehicle3 = "Toyota Camry";
$bodystyle = "sedan";
$mileage = "30,000";
$hi = null;
$model = "Camry";
$exterior = "red";
$interiorspec = "black cloth";
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
echo "<textarea name='' id='' style='width: 565px;' rows='8' cols='60'>";
echo $introduction." ".$colortxt;
echo "</textarea>";
echo "<br><br>";
?>
In this case $introduction should not be displayed as $hi = null
I can't get empty([$finalvehicle3, $bodystyle, $mileage, $hi]) to work.
I was able to use:
if (empty($hi)
|| empty($finalvehicle3)
|| empty($bodystyle)
|| empty($mileage)){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle."
with ".$mileage." miles.";
}
Will that not work?
Check if both variables are not empty echo them out:
if (!empty($introduction) && !empty($colortxt)) {
echo $introduction." ".$colortxt;
}
As a side, while coding style has personal preference, where you set these variables seems awkward as you set them to empty based on a condition, but logically (my logical at least) is to instead preset them to empty and add data if the data exists.
INSTEAD of your code here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Do this:
$introduction = "";
$colortxt = "";
if (!empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true) {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (!empty([$model, $exterior, $interiorspec]) == true) {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Just looks cleaner to me :)
I'd also not create a new array to check multiple variables, and would do:
if (
!empty($finalvehicle3)
&& !empty($bodystyle)
&& !empty($mileage
&& !empty($hi)
) {
To clarify (not intended to take away from the other answers); only isset() can accept multiple comma-separated values, and not empty().
The manuals state:
on empty():
bool empty ( mixed $var )
on isset()
bool isset ( mixed $var [, mixed $... ] )
Therefore you need to separate and check if each value is empty.
I.e.:
if(empty($var1)) && empty($var2)){}
Or using the || (OR) logical operator depending on what you want to check for; if any or all are empty.
http://php.net/manual/en/language.operators.logical.php
Note:
What you used here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true)
theoretically would be a "false positive".
If anything, you will need to use the == true in a separate statement.
I.e.:
if(empty($var1)) && empty($var2) && $x_var == true){}
However, the first 2 would need the ! negation operator since you're checking if something is true.
I.e.:
if(!empty($var1)) && !empty($var2) && $x_var == true){}

php loop display result if isset and matches the given value

I am sorry to ask such a question but am bit confused about this.
I am having simple variables defined.
$a =1;
$b=2;
$c=3;
$d="";
for($i=0;$i<10;$i++)
{
$testa = 1;
$testb = 4;
$testc = 3;
$testd = 7;
if($a!="" || $b!="" || $c!="" || $d!="") {
if($a==$testa && $b==$testb && $c==$testc && $d==$testd) {
echo $testa;
echo $testb;
echo $testc;
echo $testd;
}
}
}
This is sample php code.
what I need is that I have variables defined at top. SO in my loop i want to display result if user has any 1 variable but in below loop display result based on "and" parameter.
I actually want to skip the empty variable. SO in this case, I want as $d is empty, so it should be prevented somehow from if($a==$testa && $b==$testb && $c==$testc && $d==$testd) from here.
Any help is really appreciated.
To skip the empty values from the check, use ||
if ( ... && (empty($d) || $d == $testd)) {
Then if you also want to skip it in your echos :
echo !empty($d) ? $testd : '';

Exclude form fields from POST request

I have a simple foreach statement grabbing all the fields from a submitted form. The fields are then put into a table that is sent via email. There are 3 fields that I need submitted and validated, but not sent with the email. Here is my script generating the table:
foreach($_POST as $name => $value) {
if($name !== "num1" || $name !== "num2" || $name !== "captcha") {
$text .= "<tr><td>$name</td><td>";
//if form field is array
if(is_array($value)) {
foreach($value as $symptom) {
$text .= $symptom . ", ";
}
//else no array
} else {
$text .= $value;
}
$text .= "</td></tr>";
}
}
Basically all form field names are set as $name and all values are set as $value. I am trying to include all fields except the ones named num1, num2, & captcha.
I am not redoing the way this form is handled, I just need to exclude these 3 fields from the table but my conditional statement isn't doing what I had expected. How can I ensure these three fields won't be included in the email?
change if($name !== "num1" || $name !== "num2" || $name !== "captcha")
to if($name !== "num1" && $name !== "num2" && $name !== "captcha")
Change the || in your if() to &&. Your if() as written will ALWAYS succeed, because whatever value you're testing will always "not be" any of those values at the same time.
PHP's continue will skip an interation of a loop, then you change to using == comparison operators... Try this:
if($name == "num1" || $name == "num2" || $name == "captcha")
continue;
else {
// rest of your code
}
You should use && instead of || in if statement.

skipping through foreach with multiple conditions

I'm trying to get my foreach to skip certain children in the xml based on one of the childrens values. The first code works for skipping just 1 but I want to skip a lot. The second code won't skip any of them.
<?php
$gamespage = simplexml_load_file("http://gamepage.com/games?xml=1");
foreach($gamespage->games->game as $game)
{
$gid = $game->appID;
if ($gid != 65920) {
} }
second code (not skipping any):
<?php
$gamespage = simplexml_load_file("http://gamepage.com/games?xml=1");
foreach($gamespage->games->game as $game)
{
$gid = $game->appID;
if ($gid != 65920 || $gid != 40940 || $gid != 50110 || $gid != 8990) {
} }
You need to use && instead of ||
Or even better
if (!in_array($gid, array(65920, 40940, ...)))

Categories