5

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?

1
  • I'd put them all in one array array(1,10,11,20,21,30) and do a binary search. The found key(s) will tell you which group it belongs to. Commented May 6, 2014 at 14:53

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

0

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];

Comments

0

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;
    }
}

3 Comments

Did you just copy @BartłomiejWach's answer (badly...)?
It's not rocket science!, I was actually writing mine when he posted his, don't need to copy dude...
you'd probably want printf instead of sprintf here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.