Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way of determining in which range a number is?

Tags:

php

My application generates a random integer between 0 and 1000.

I have 5 ranges: 0-50, 51-250, 251-500, 501-700, 701-1000. (Note that the range sizes are not equal.)

I will call these ranges: "0","50","250","500","700", respectively (will store those names in my database).

I know that i could do the following:

if ($number > 700 && $number <=1000)
       $num_range='700';

else if... 

... and so on.

But is there a more efficient way of doing it?

Thanks a lot in advance. Regards

like image 288
alexx0186 Avatar asked Dec 04 '22 02:12

alexx0186


1 Answers

Utilize elseif efficiently:

if($number <= 50)
    $num_range='0';
elseif($number <= 250)
    $num_range='50';
elseif($number <= 500)
    $num_range='250';
elseif($number <= 700)
    $num_range='500';
elseif($number <= 1000)
    $num_range='700';
...
like image 121
Naftali Avatar answered Jan 18 '23 08:01

Naftali