cj333
cj333

Reputation: 2609

php compare value if not

there have two value, $a and $b. I need make a judge, $a is not 3 times as bigger as b or $b is not 3 times as bigger as $a, echo $a.' and '.$b; else not.

for explain:

if $a = 5, $b=1 so $b*3 = 3, $b*3 < $a, then echo 'nothing';

if $a = 5, $b=2 so $b*3 = 6, $b*3 > $a, then echo $a.'&nbsp;and&nbsp;'.$b;//5 and 6

if $b = 5, $a=1 so $a*3 = 3, $a*3 < $b, then echo 'nothing';

if $b = 5, $a=2 so $a*3 = 6, $a*3 > $b, then echo $a.'&nbsp;and&nbsp;'.$b;//6 and 5

one of my code:

$a='5';
$b='1';
if ((!($a>=($b*3))) or (!($b>=($a*3)))){
    echo $a.'&nbsp;and&nbsp;'.$b; //this may be echo 'nothing'
}else{
  echo 'nothing';
}

Upvotes: 1

Views: 104

Answers (6)

Wissam Youssef
Wissam Youssef

Reputation: 830

I would make it much simpler than that. I like to always follow KISS. If a person needs more than 5 seconds to read and to understand my line I would scrap it.

I would make a quick check which is smaller or bigger, then check if they are 3 times bigger or not.Maybe not as "efficient" as yours. but meh :).

function checkAandB($a,$b){
    if $a >= $b             //I assumed that if equal then it doesn't matter
         $smaller = $b;
         $bigger = $a
     else
         $smaller = $a;     //fixed a typo in here
         $bigger = $b;
    if $smaller < (3 * $bigger )
         do nothing
    else 
        echo $a and $b

It's pseudocode :) converted to your suitable language.

Upvotes: 1

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

function compareAB($a, $b) {
  return ($a < ($b * 3)) && ($b < ($a * 3)) ? "$a and $b" : "nothing";
  }

echo compareAB(5,1); // nothing
echo compareAB(5,2); // 5 and 2

Upvotes: 0

Joe Phillips
Joe Phillips

Reputation: 51200

//if $a = 5, $b=1 so $b*3 = 3, is still smaller than $a, then echo 'nothing';
if ($a > $b) && ($a > $b*3) { echo 'nothing'; }

//if $a = 5, $b=2 so $b*3 = 6, is bigger than $a, then echo $a.'&nbsp;and&nbsp;'.$b;//5 and 6
if ($a > $b) && ($a < $b*3) { echo $a . ' and ' . $b; }

//if $b = 5, $a=1 so $a*3 = 3, is still smaller than $b, then echo 'nothing';
if ($b > $a) && ($b > $a*3) { echo 'nothing'; }

//if $b = 5, $a=2 so $a*3 = 6, is bigger than $b, then echo $a.'&nbsp;and&nbsp;'.$b;//6 and 5
if ($b > $a) && ($b < $a*3) { echo $a . ' and ' . $b; }

What if $a==$b?

Upvotes: 1

Matt
Matt

Reputation: 754

From your examples, you seem to want to print 'nothing' if the values are very different, but if the values are close (within a factor of 3) then you print the values.

You just need to fix the logic in your test line:

if ($a < $b * 3 && $b < $a * 3) {

Upvotes: 1

Xi 张熹
Xi 张熹

Reputation: 11071

is this what you are asking?

function checkAandB($a, $b) {
if($a==0 || $b==0)
return true; else if ($a/$b>=3 || $b/$a>=3) return true; else return false }

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227310

Replace $a[0], $a[1], $b[0], and $b[1] with $a, $a, $b, and $b, respectively.

Upvotes: 3

Related Questions