How to do decompose conditional refactoring? - php

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;
}

Related

I need assistance with compacting my working PHP code

I was just working on a customer project and I am wondering if someone know how to make this code more compacter:
$box_size_unknown =
$cart_item['f_box_L'] <= 0 || !$cart_item['f_box_L']
||
$cart_item['f_box_H'] <= 0 || !$cart_item['f_box_H']
||
$cart_item['f_box_D'] <= 0 || !$cart_item['f_box_D'];
I'm a new member. Sorry if my answer is incomplete or wrong.
<?php
function cars($ic){
$cart_item = array('f_box_L','f_box_H','f_box_D');
$cll = $cart_item[0];
$clh = $cart_item[1];
$cld = $cart_item[2];
$box_size_unknown = $cll <= 0 || !$cll || $clh <= 0 || !$clh ||
$cld <= 0 || !$cld;
$ic = $box_size_unknown;
echo $ic;
}
echo cars(0);
?>
Use the function I want to describe.

PHP: Multiple Unique Random Integers In A Specific Range

I want to create 8 random integers, that are unique and in the range between 0 and 99.
Is there a neater solution, than the one that I thought of?
<?php
do {
$rnd1 = rand(0,99);
$rnd2 = rand(0,99);
$rnd3 = rand(0,99);
$rnd4 = rand(0,99);
$rnd5 = rand(0,99);
$rnd6 = rand(0,99);
} while (($rnd1 == $rnd2) ||
($rnd1 == $rnd3) ||
($rnd1 == $rnd4) ||
($rnd1 == $rnd5) ||
($rnd1 == $rnd6) ||
($rnd2 == $rnd3) ||
($rnd2 == $rnd4) ||
($rnd2 == $rnd5) ||
($rnd2 == $rnd6) ||
($rnd3 == $rnd4) ||
($rnd3 == $rnd5) ||
($rnd3 == $rnd6) ||
($rnd4 == $rnd5) ||
($rnd4 == $rnd6) ||
($rnd5 == $rnd6) );
?>
Try the code below.
It will create an array containing 8 random values between 0 and 99 while checking if they have been added already to ensure they are unique across.
$numbers = array();
while ( count($numbers) <= 8 ) {
$x = mt_rand(0,99);
if ( !in_array($x,$numbers) ) {
$numbers[] = $x;
}
}
print_r($numbers);
Also see these two Q&A's about using mt_rand vs. rand
Difference between mt_rand() and rand()
What's the disadvantage of mt_rand?
This is an optimized version that relies on the array indexes. The complexity of this solution is linear rather than n2 as in #AlexAndrei's answer. It relies on using array indexes as the guarantee there are no duplicates so there is no need to add the overhead of in_array.
$random_numbers = [];
do {
$rand = rand(0, 99);
$random_numbers[$rand] = $rand;
} while( count($random_numbers) < 9 );
$random_numbers = array_values($random_numbers); // This strips the keys
print_r($random_numbers);
If you are using a foreach you can even drop the array_values call which would also increase the speed of your code, but the numbers in the array will be in the form: [ a => a, b => b, ... ]
$rnds = [];
do {
$newRnd = rand(0, 99);
$rnds[] = $newRnd;
} while(in_array($newRnd, $rnds) && count($rnds) < 9);
print_r($rnds);

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 ;
}

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

PHP: Conditional statement with possible empty variables

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 == '')

Categories