简体   繁体   中英

How to check if a number falls in a given range

I have a variable $user_id (number value)

Want to check if $user_id falls in between the range of 1 - 1000 or 1001 - 2000 or 2001 - 3000.... 99001 - 100000

  1. Is there a way to do this without writing 100 switch or if statements in PHP?
  2. When it finds the match, execute a code.

I know while and for loops are required for this. But not able to code it properly.

This the simplest way:

    $check = 0;
    $nextCheck = $check+1001;
    while ($check < 100001) {
    If ($user_id > $check && $user_id < $nextCheck) {
      // Code ...
      break;
    } else {
       $check+=1000;
       $nextCheck+=1000;
    }
    }

You can just divide the number by 1000 since you have a 1000 interval range in a consecutive way.

The quotient * 1000 + 1 is your start value for the interval with an exceptional corner case of a number divisible by 1000, which would just be the border end for an interval.

<?php

$tests = [1,999,1000,50001,100000,2999];

foreach($tests as $test_case){
    $quotient = intval($test_case / 1000);
    if($test_case % 1000 === 0){
        $start = $test_case - 1000 + 1;
        echo "$test_case : Range: ($start - $test_case)",PHP_EOL;
    }else{
        $start = $quotient * 1000 + 1;
        $end = ($quotient + 1) * 1000;
        echo "$test_case : Range: ($start - $end)",PHP_EOL;
    }
}

Output:

1 : Range: (1 - 1000)
999 : Range: (1 - 1000)
1000 : Range: (1 - 1000)
50001 : Range: (50001 - 51000)
100000 : Range: (99001 - 100000)
2999 : Range: (2001 - 3000)

Demo: https://3v4l.org/apbqV

Do not generate an array. Do not use a loop. Use math to determine the upper limit of the range, then subtract 999 from that number -- done.

*my snippet assumes we are only dealing with positive values between 1 and 100000.

Code: ( Demo )

$tests = [1, 999, 1000, 50001, 100000, 2999];

foreach ($tests as $test) {
    $upper = intval(($test - 1) / 1000) * 1000 + 1000;
    echo "$test is between " . ($upper - 999) . " and $upper\n";
}

Output:

1 is between 1 and 1000
999 is between 1 and 1000
1000 is between 1 and 1000
50001 is between 50001 and 51000
100000 is between 99001 and 100000
2999 is between 2001 and 3000

Formula Breakdown:

intval(            #3) remove decimals from difference
    ($test - 1)    #1) subtract one
    / 1000         #2) divide by 1000
)
* 1000             #4) multiply integer by 1000
+ 1000             #5) add 1000

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