5

I have an array which stores numbers. The count of numbers varies time to time. There is another variable which a holds number, and I need to find out in which range $num falls. In the above case $num falls under 64. (Bigger than 32 and less than 64)

$ar = array(0, 32, 64, 96, 128, 160, 192, 224);

$num = 44;

How do I crack this?

2
  • First sort the array then find index of your number then one below and one above that are your answers Commented May 17, 2013 at 11:29
  • @ØHankyPankyØ, the array contains only the ranges, not the used number. Commented May 17, 2013 at 11:48

2 Answers 2

7
$ar = array(0, 32, 64, 96, 128, 160, 192, 224);

$num = 44;

$range = min(array_filter($ar, function($i) use($num) {
    return $i > $num;
}));

var_dump($range);

Online demo: http://ideone.com/KV6MWD

Sign up to request clarification or add additional context in comments.

6 Comments

I like this Zmayte. If only there was a nice way to terminate array_filter() only.
With a sorted array, you can also do this in O(log n) time, instead of the O(n) time that a linear scan would take. You simply do a binary search until the left and right choices are lower and higher than your number.
@SubSevn: with sorted array - yes
@SubSevn That would be after you profiled your application and determined this particular part of code to be the bottleneck, right? ;)
Nice solution, add an example also with for the number before, like $range = max(array_filter($ar, function($i) use($num) { return $i < $num; }));
|
0

PHP8.4 gave birth to a new family of short circuiting functions -- one that suits your task perfectly. Demo

$ar = [0, 32, 64, 96, 128, 160, 192, 224];

$num = 44;

var_export(
    array_find($ar, fn($v) => $v > $num)
);
// 64

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.