AHinson AHinson - 6 months ago 9
PHP Question

Comparing a number to each value in array

I have users submit tempos(number) and I would like to compare that number to an array of preset numbers and return one value that is the next number up from it.

For example:


  • Submitted tempo - 145

  • Numbers in preset array - 104, 116, 128, 140, 152, 164, 176

  • Desired return - 152



I have been messing around with the
array_filter
php function but I haven't come up with anything worth posting here yet. I was wondering if anyone had any other ideas about how I might achieve this.

Answer

Such questions should be posted in StackOverflow. But there you go:

$numbers = array( 104, 116, 128, 140, 152, 164, 176 );
$tempo = 145;
$found = false;
ksort( $numbers ); // sort in an ascending order
foreach( $numbers as $number ) { if( $number > $tempo ) { $found = $number; break; } }
print_r( $found ); // int|false