Forum Moderators: coopster

Message Too Old, No Replies

Max Value Within Range

find the max value within a range from an array

         

Kings on steeds

11:08 am on Feb 1, 2010 (gmt 0)

10+ Year Member



I need a way to get the largest value that is in a range from an array.


$array = (12,13,26,45,53,89);
$range = range(12,30);
$number = max_in_range($range,$array)

// output $number = 26

I am just not quite sure what my max_in_range would look like? my head just in earth at the moment, can anyone poke me in the right direction please?

Many Thanks,
Alan

Kings on steeds

11:24 am on Feb 1, 2010 (gmt 0)

10+ Year Member



Update:

Ok, so now i have a methods, but I wonder if maybe there is a better way.


//holder for our category
$our_cat;
// this is our array of id's
$ids = explode(',',$_product->_data['category_ids']);
// our range.
$range = range(54,154);
// sort array to send highest number to the end.
sort($ids);
// loop through, and set our id to $our_cat
foreach($ids as $i){
if(in_array($i,$range)){ $our_cat = $i; }
}

with the above code, our_cat will equal the highest value in my range, but, is there a better way still?

Many Thanks,
Alan.

Readie

5:05 pm on Feb 1, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$number = max_in_range($range, $array);

function max_in_range($ran, $arr) {
$value_count = count($arr);
$min_range = min($ran);
$max_range = max($ran);
for($i = 0; $i < $value_count; $i++) {
if(($arr[$i] >= $min_range) || ($arr[$i] <= $max_range)) {
$range_array[$i] = $arr[$i];
}
}
$output = max($range_array);
return $output;
}

That should do the job.

Readie

6:27 pm on Feb 1, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



oops, made a mistake there.

if(($arr[$i] >= $min_range) || ($arr[$i] <= $max_range)) { 

Should be:

if(($arr[$i] >= $min_range) && ($arr[$i] <= $max_range)) { 

coopster

12:07 pm on Feb 2, 2010 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



but, is there a better way still?


There is more than one way to do it, as they often say. array_intersect() will certainly streamline the code for you ...
$array = array(12,13,26,45,53,89); 
$range = range(12,30);
$number = max(array_intersect($range,$array));
print '<pre>';
print_r($array);
print_r($range);
print $number;
print '</pre>';
exit;