PHP: Conditional statement with possible empty variables - php

I'm creating a custom search form and when I try and sort the results I get all the objects displayed instead of the matched criteria. The reason I discovered was that some of the inputs from the form don't have a default value and when this is not declared in the conditional statement later on (for sorting) it just shows all the objects, whether the other requirements are met or not. I tried applying an OR statement with the specific variables able to be empty, but it gave the same result. Like so -
<?php if ($bedrooms >= $min_rooms
&& $bedrooms <= $max_rooms
&& $space >= $min_space
&& $space <= $max_space
&& $price >= $min_price
&& $price <= $max_price
&& $sel_type == $type
|| $sel_type == ''
&& $country == $sel_country
|| $sel_country == '' ) { ?>
(See the last two statements)
I was thinking of checking each variable in the conditional statement before including it but it feels like unnecessary code. How would you do it?

The && operator has a higher precedence than the || operator, so your expression is currently grouped like this, probably not what you want:
($bedrooms >= $min_rooms && $bedrooms <= $max_rooms && $space >= $min_space && $space <= $max_space && $price >= $min_price && $price <= $max_price && $sel_type == $type)
||
($sel_type == '' && $country == $sel_country)
||
($sel_country == '' )
Try adding parentheses like this to achieve correct grouping:
($bedrooms >= $min_rooms && $bedrooms <= $max_rooms && $space >= $min_space && $space <= $max_space && $price >= $min_price && $price <= $max_price && ($sel_type == $type || $sel_type == '') && ($country == $sel_country || $sel_country == '') )

Your expression may fail as the && operator has a higher precedence than the || operation. That means an expression like this:
… && $sel_type == $type || $sel_type == ''
is equivalent to this (operator precedence highlighted by using parentheses):
(… && $sel_type == $type) || $sel_type == ''
To fix that put the || expressions in parentheses:
$bedrooms >= $min_rooms && $bedrooms <= $max_rooms && $space >= $min_space && $space <= $max_space && $price >= $min_price && $price <= $max_price && ($sel_type == $type || $sel_type == '') && ($country == $sel_country || $sel_country == '')
Additionally, your expression is probably easier to read and to maintain if you use some helper functions like a between function:
function between($val, $min, $max) {
return $min <= $val && $val <= $max;
}
Then your expression reads:
between($bedrooms, $min_rooms, $max_rooms) && between($space, $min_space, $max_space) && between($price, $min_price, $max_price) && ($sel_type == $type || $sel_type == '') && ($country == $sel_country || $sel_country == '')

Related

PHP if title contains $variable

I have my variable, $mustcontain and I have the following:
if ($getvideoviews >= $minimumvideoviews
AND $getvideolikes >= $minimumvideolikes
AND $VidDuration >= $minvidlenght
AND $getchannelsubscribers >= $minsubs)
What I need is to check if $videotitle contains what´s in $mustcontain and if true then proceed to show some more information
You can use strpos() or in_array():
If $mustcontain is a string:
if ($getvideoviews >= $minimumvideoviews
&& $getvideolikes >= $minimumvideolikes
&& $VidDuration >= $minvidlenght
&& $getchannelsubscribers >= $minsubs
&& strpos($videotitle, $mustcontain) !== false) {
// do sth. with it
}
If $mustcontain is an array:
if ($getvideoviews >= $minimumvideoviews
&& $getvideolikes >= $minimumvideolikes
&& $VidDuration >= $minvidlenght
&& $getchannelsubscribers >= $minsubs
&& in_array($videotitle, $mustcontain) !== false) {
// do sth. with it
}

php search within string for word?

I'm using PHP's preg_match to help determine the value of a string.
But the code only ever prints 1 or 2.
Why aren't the last two cases of my if statement ever matched?
$atype = strtolower($userData['user_type']); // let say data is :: company introducer
if ($atype == "individual introducer" || $atype == "individualintroducer" ||
(preg_match('/i/',$atype) AND preg_match('/int/',$atype)) ) {
$atype = 1 ;
} elseif ($atype == "individual investor" || $atype == "individualinvestor" ||
(preg_match('/i/',$atype) AND preg_match('/inv/',$atype)) ) {
$atype = 2;
} elseif ($atype == "company introducer" || $atype == "companyintroducer" ||
(preg_match('/c/',$atype) AND preg_match('/int/',$atype)) ){
$atype = 3;
} elseif ($atype == "company investor" || $atype == "companyinvestor" ||
(preg_match('/c/',$atype) AND preg_match('/inv/',$atype)) ){
$atype = 4;
}
echo $atype;
You need to explain your question in a better way.
But i guess as you say the data assumed is company introducer.
So it already matches condition for the first if block.
For ex:
In company introducer
The preg_match will return true.
if($atype == "individual introducer" || $atype == "individualintroducer" || (preg_match('/i/',$atype) AND preg_match('/int/',$atype)) ){
$atype =1 ;
}

How to do decompose conditional refactoring?

I've this situation in code where i think the code is unnecessary complex and i believe i can refactor it to make it more easier to understand and read.
So i googled about it and found decompose conditional refactoring, but i'm still in doubt how to do refactoring
if(count($bagTypes) == 1 && (array_key_exists('type1', $bagTypes)
|| array_key_exists('type2', $bagTypes)
|| array_key_exists('type3', $bagTypes))){
$flag = 1;
}
if(count($bagTypes) == 2 && (
(array_key_exists('type1', $bagTypes) && array_key_exists('type2', $bagTypes)) ||
(array_key_exists('type1', $bagTypes) && array_key_exists('type3', $bagTypes)) ||
(array_key_exists('type2', $bagTypes) && array_key_exists('type3', $bagTypes)))
){
$flag = 1;
}
Is there any better way of doing this?
You could try something like this:
$arrayKeys = array(
'type1',
'type2',
'type3'
);
$bagTypesKeys = array_keys($bagTypes);
if ((count($bagTypes) == 1 && count(array_diff($arrayKeys, $bagTypesKeys)) < 3)
|| (count($bagTypes) == 2 && count(array_diff($arrayKeys, $bagTypesKeys)) < 2))
{
$flag = 1;
}

entry level issue: || (OR) operator

When I use the || (OR) operator in my if statement below I end up in an endless loop.
For sake of simplicity here is the var_dump:
$auth "0"
$id "2"
$enabled "1"
$page "auth-login.php"
If the criteria below is not met in the if statement then it will forward the user to auth-login.php (this is not applicable if the current $page is auth-login.php and auth-login-validate.php).
Statement without || (OR) operator: Forwards to auth-login.php as intended, but must also include auth-login-validate.php
if ($auth == '0' && $id != '1' && $enabled == '1' && $page != 'auth-login.php') {
header('Refresh: 0; URL=auth-login.php');
die();
}
Statement with || (OR) operator: Forwards to auth-login.php endlessly in a loop.
if ($auth == '0' && $id != '1' && $enabled == '1' && $page != 'auth-login.php' || $auth == '0' && $id != '1' && $enabled == '1' && $page != 'auth-login-validate.php') {
header('Refresh: 0; URL=auth-login.php');
die();
}
Will be some precedence related error. Make sure to put the parentheses where you intend to encapsulate the "OR" parts

PHP basic comparison with negative

I cannot find an answer to this and I am sure it is right in front of me. How do I say in PHP as part of an IF statement the following:
if NOT ( (variable1 == 10) && (variable2 == 20) )
Thanks!
You can use ! to achieve this
if ( (variable1 != 10) || (variable2 != 20) )
Or simply
if (!((variable1 == 10) && (variable2 == 20)))
if NOT ( (variable1 == 10) && (variable2 == 20) )
==>
if (! ( (variable1 == 10) && (variable2 == 20) ) )
<==>
if ( (variable1 != 10) ||(variable2 != 20) )
! mean not
so U can use it like this
if (! ( ($variable1 == 10) && ($variable2 == 20) ) )
or
if ( ($variable1 != 10) ||($variable2 != 20) )
&& will be || because !&& = ||
and U can't use variable1 without $ if U don't define it like this
define('variable1','value of variable1');
but then U can't change it's value so if statement will always have the same result and for that U should use $variable1

Categories