Question

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?

Était-ce utile?

La solution

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

Autres conseils

an even faster way would be to create a lookup array, in which the user input is the key for the group label:

 $lookup = array( 1 => 'group A',
                  2 => 'group A',
                 //..
                 10 => 'group B' //, ...
                );

 echo 'you are in ' . $lookup[$input];

of course, the lookup array would be rather big (mostly for us humans, not so much for the server). If you have a pattern in your input values (in your example it seems like it's a range of 10s), you could calculate a hash as key:

 $lookup = array( 0 => 'group A',
                  1 => 'group B' //,....
                );
 $hash = floor($input / 10);

 echo 'you are in ' . $lookup[$hash];

If you have your arrays stored in an array $groups for example you can use the following loop, and then break when you find the right group:

foreach($groups as $i => $group) {
    if ($input >= $group[0] && $input < $group[1]) {
        printf("You are in group %d", $i);
        break;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top