developer tip

정수가 범위 내에 있는지 확인하는 방법은 무엇입니까?

optionbox 2020. 11. 13. 08:05
반응형

정수가 범위 내에 있는지 확인하는 방법은 무엇입니까?


이 중복 코드를 수행하지 않고 범위를 테스트하는 방법이 있습니까?

if ($int>$min && $int<$max)

?

함수처럼 :

function testRange($int,$min,$max){
    return ($min<$int && $int<$max);
}

용법:

if (testRange($int,$min,$max)) 

?

PHP에 이러한 내장 기능이 있습니까? 아니면 다른 방법이 있습니까?


나는 당신이 당신의 기능보다 더 나은 방법을 얻을 것이라고 생각하지 않습니다.

깨끗하고 따라하기 쉽고 이해하기 쉬우 며 상태의 결과를 반환합니다 ( return (...) ? true : false엉망이 아님).


1000000-times-loop로 세 가지 방법을 테스트했습니다.

t1_test1 : ($val >= $min && $val <= $max): 0.3823ms

t2_test2 : (in_array($val, range($min, $max)): 9.3301ms

t3_test3 : (max(min($var, $max), $min) == $val): 0.7272ms

T1은 가장 빠르며 기본적으로 다음과 같습니다.

function t1($val, $min, $max) {
  return ($val >= $min && $val <= $max);
}

아무 내장 기능은 없지만, 당신은 쉽게 함수를 호출하여 그것을 달성 할 수 min()max()적절하게.

// Limit integer between 1 and 100000
$var = max(min($var, 100000), 1);

주어진 예제의 대부분은 테스트 범위 [$ a .. $ b], $ a <= $ b에 대해 가정합니다. 즉, 범위 극단은 더 낮은-더 높은 순서이고 대부분은 모두 정수라고 가정합니다.
그러나 여기에 설명 된대로 $ n이 $ a와 $ b 사이에 있는지 테스트하는 함수가 필요했습니다.

Check if $n is between $a and $b even if:
    $a < $b  
    $a > $b
    $a = $b

All numbers can be real, not only integer.

테스트하는 쉬운 방법이 있습니다.
나는 사실에 시험을 기반으로 그 ($n-$a)($n-$b)다른 부호 $를 N $ a와 $ B 사이, 같은 기호 $ n은 $ A .. $ B 형 범위를 벗어났습니다.
이 함수는 증가, 감소, 양수 및 음수를 테스트하는 데 유효하며 정수만 테스트하는 데 제한되지 않습니다.

function between($n, $a, $b)
{
    return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}

나는 댓글을 달 수 없으므로 (평판이 충분하지 않음) 여기에서 Luis Rosety의 답변을 수정하겠습니다.

function between($n, $a, $b) {
    return ($n-$a)*($n-$b) <= 0;
}

이 함수는 n == a 또는 n == b 인 경우에도 작동합니다.

Proof: Let n belong to range [a,b], where [a,b] is a subset of real numbers.

Now a <= n <= b. Then n-a >= 0 and n-b <= 0. That means that (n-a)*(n-b) <= 0.

Case b <= n <= a works similarly.


There's filter_var() as well and it's the native function which checks range. It doesn't give exactly what you want (never returns true), but with "cheat" we can change it.

I don't think it's a good code as for readability, but I show it's as a possibility:

return (filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]]) !== false)

Just fill $someNumber, $min and $max. filter_var with that filter returns either boolean false when number is outside range or the number itself when it's within range. The expression (!== false) makes function return true, when number is within range.

If you want to shorten it somehow, remember about type casting. If you would use != it would be false for number 0 within range -5; +5 (while it should be true). The same would happen if you would use type casting ((bool)).

// EXAMPLE OF WRONG USE, GIVES WRONG RESULTS WITH "0"
(bool)filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]])
if (filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]])) ...

Imagine that (from other answer):

if(in_array($userScore, range(-5, 5))) echo 'your score is correct'; else echo 'incorrect, enter again';

If user would write empty value ($userScore = '') it would be correct, as in_array is set here for default, non-strict more and that means that range creates 0 as well, and '' == 0 (non-strict), but '' !== 0 (if you would use strict mode). It's easy to miss such things and that's why I wrote a bit about that. I was learned that strict operators are default, and programmer could use non-strict only in special cases. I think it's a good lesson. Most examples here would fail in some cases because non-strict checking.

Still I like filter_var and you can use above (or below if I'd got so "upped" ;)) functions and make your own callback which you would use as FILTER_CALLBACK filter. You could return bool or even add openRange parameter. And other good point: you can use other functions, e.g. checking range of every number of array or POST/GET values. That's really powerful tool.


Using comparison operators is way, way faster than calling any function. I'm not 100% sure if this exists, but I think it doesn't.


You could do it using in_array() combined with range()

if (in_array($value, range($min, $max))) {
    // Value is in range
}

Note As has been pointed out in the comments however, this is not exactly a great solution if you are focussed on performance. Generating an array (escpecially with larger ranges) will slow down the execution.

참고URL : https://stackoverflow.com/questions/5029409/how-to-check-if-an-integer-is-within-a-range

반응형