简体   繁体   中英

PHP Comparison for one less than

Google really let me down for this one. I want to do a comparison for less than or greater than but only by 1. So I can detect if say value B is one less than or one greater than A.

if (A is one less than B || A is one greater than B) {
 return true
}

That's what I want to do.

If you always want to check if its one above or one below, differentiate the two, and see if the absolute value of the result is one.

if (abs($a - $b) === 1) {
    // Do your thing
}

See this live demo .

Do a standard equality test.

Just perform the subtraction or addition on the value you're comparing to.

3 === (4-1)

Something like this. As long as the different between $a and $b is 1 .

if(abs($a - $n) == 1) {...}

Translating your pseudo condition:

(A is one less than B) or (A is one greater than B)

this becomes:

if ( $A === $B-1 || $A === $B+1 ) {
  return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM