How to determine if two random values are close?

1

I have a question that I would like answers for.

I have a RAND function that generates values from 1 to 20.

What I want to do is:

Se o valor $rand1 tiver perto do valor $rand2
echo ok

How do I say "Close to" in PHP?

    
asked by anonymous 16.06.2017 / 15:44

2 answers

8

Yes, the path is what @rray commented:

function perto($a, $b)
{
    $limite = 2;
    return abs($a - $b) <= $limite;
}

if(perto($rand1, $rand2)) {
    echo 'perto';
}
    
16.06.2017 / 15:57
1

Try this logic, I did not try to put it on my cell phone.

if ($rand1 > $rand2) {
    if ($rand1 - $rand2 == 1) {
        echo "Esta perto";
    }
    else {
        echo "Está longe";
    }
}
else if ($rand2 > $rand1) {
    if ($rand2 - $rand1 == 1) {
        echo "Esta perto";
    }
    else {
        echo "Está longe";
    }
}
    
16.06.2017 / 16:05