Re: Finding if a number is in the range

From: Date: Fri, 18 May 2001 03:35:18 +0000
Subject: Re: Finding if a number is in the range
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-53380@lists.php.net to get a copy of this message
Or just use a simple chain of if statements :) if ($num >= 200 && $num <= 299) { echo "$num is between 200 and 299"; } else if ($num >=1000 && $num <= 2263) { echo "$num is between 1000 and 2263"; } else if ($num >=2264 && $num <= 2499) { echo "$num is between 2264 and 2499"; } else { echo "$num is not between 200 and 299, 1000 and 2263 or 2264 and 2499"; } If you have a large number of these to do, you could store your upper and lower bounds in an array and use a loop to process the bounds. ie. // set up our bounds $bounds = array ( -10, -1, 0, 199, 200, 299, 1000, 2263, 2264, 2499 ); // make sure that we have a matched sets of bounds // the bounds array should have at least 2 elements // and the remainer (modulus) of $count / 2 should be 0 $count = count ($bounds); $count > 1 AND 0 === ($count % 2) OR die ('The $bounds array must contain one or more matched elements.'); for ($index = 0; $index < $count; $index += 2) { if ($number >= $bounds[$index] && $number <= $bounds[$index + 1]) { $between = sprintf ("%s is between %s and %s.", $number, $bounds[$index], $bounds[$index + 1]); break; } } if (isset ($between)) { echo $between; } else { // join the bounds into a string separated by .. $bounds = join ('..', $bounds); // convert every second set of .. to <br> $bounds = ereg_replace ('([^.]+\.\.[^.]+)\.\.', '\1<br>', $bounds); echo "Number $number not found with any of the specified ranges:<blockquote>$bounds</blockquote>"; } --zak ----- Original Message ----- From: "MaD dUCK" <madduck@madduck.net> To: "Joseph Blythe" <joe.blythe@binarylogic.com.au> Cc: <php-general@lists.php.net> Sent: Thursday, May 17, 2001 7:53 PM Subject: Re: [PHP] Finding if a number is in the range > also sprach Joseph Blythe (on Fri, 18 May 2001 11:12:23AM +0930): > > How do I find if a number is in a range example: > > assuming that the ranges are continuous, make an array of the first > number for each range and then implement a custom binary search for > O(lg n) performance. > > martin; (greetings from the heart of the sun.) > \____ echo mailto: !#^."<*>"|tr > "<*> mailto:" net@madduck > -- > "i wish there was a knob on the tv to turn up the intelligence. > there's a knob called 'brightness', but it doesn't seem to work." > -- gallagher > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, e-mail: php-general-unsubscribe@lists.php.net > For additional commands, e-mail: php-general-help@lists.php.net > To contact the list administrators, e-mail: php-list-admin@lists.php.net >

« previous php.general (#53380) next »