Wednesday, June 22, 2011

PHP - Check a number from a range of numbers exists in an array of range of numbers.

suppose u have an array like appended below:

$arr[0][0]=200;
$arr[0][1]=400;

$arr[1][0]=401;
$arr[1][1]=900;

$arr[2][0]=100;
$arr[2][1]=700;

$arr[3][0]=901;
$arr[3][1]=901;

and you want to find any number from the range suppose 400-600 exists in the above array.
Of course 400-600 exists in the ranges (200-400,401-900,100-700)

Example:

$arr=array();

$arr[0][0]=200;
$arr[0][1]=400;

$arr[1][0]=401;
$arr[1][1]=900;

$arr[2][0]=100;
$arr[2][1]=700;

$arr[3][0]=901;
$arr[3][1]=901;

##########################
#range of numbers to check
$start=400;
$end=600;

$data=number_exists_in_array_of_number_range($start,$end,$arr);

if($data<>""):

//////////////////////////////////////////////////////////////////
#output the number ranges where the searching number ranges exists

foreach($data as $val) {

echo $arr[$val][0]."-".$arr[$val][1]."
";

}

endif;


#--------------------------------------------------------------------------#


function number_exists_in_array_of_number_range($start,$end,$arr) {

$i=0;

///////////////////////////////
#loop through each row of array

foreach($arr as $key=>$val) {


if(($val[0]>=$start and $val[0]<=$end) or ($val[1]>=$start and $val[1]<=$end)):

$result[$i]=$key;
$i++;

endif;

if($start>$val[0] and $end<$val[1]):

$result[$i]=$key;
$i++;

endif;

}

return $result;
}

#--------------------------------------------------------------------------#

No comments: