Search code examples
phpcomparisonoperators

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.


Solution

  • 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.