Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php find value in array range

Tags:

arrays

php

range

I have the following array:

$groupA= array(1,10);
$groupB = array(11,20);
$groupC = array(21,30);

The user has the possibility to enter any numeric value into a text-box, for example "5" now I need to display the user in which group that number is. I've done this before this way:

And then do a switch case like this:

switch ($input){
    case ($input>= $groupA[0] && $input<= $groupA[1]):
        echo "You are in Group A.";
    break;
    case ($input>= $groupB[0] && $input<= $groupB[1]):
        echo "You are in Group B.";
    break;

However, this seems not feasable since we have got many many groups (likely over 200) and using this many switch-cases is unefficient.

Any ideas on how to solve this more elegantly?

like image 370
user3608670 Avatar asked Mar 19 '23 16:03

user3608670


1 Answers

I'd make an array:

$groups = array();

$groups['groupA'] = array('min'=>1,'max'=>100);
$groups['groupB'] = array('min'=>1,'max'=>100);

And then

foreach($groups as $label => $group)
{
    if($input >= $group['min'] && $input <= $group['max'])
    {
        echo "You are in group $label";
        break;
    }
}

or you can put them in a database

like image 159
Bartłomiej Wach Avatar answered Mar 28 '23 19:03

Bartłomiej Wach