Php find value in array range

I have the following array:

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

The user has the ability to enter any numerical value in the text field, for example, "5", now I need to display the user in whose group this number is. I have done this before:

And then do 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 impossible, since we have many groups (probably more than 200), and using this large number of wiring closets is inefficient.

Any ideas on how to solve this problem more elegantly?

+4
source share
3 answers

I would 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

+4
source

, $groups, , , , :

foreach($groups as $i => $group) {
    if ($input >= $group[0] && $input < $group[1]) {
        printf("You are in group %d", $i);
        break;
    }
}
0

- , :

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

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

Of course, the search array will be quite large (mainly for us people, not for the server). If you have a pattern in your input values ​​(in your example, it looks like a range of 10 s), you can calculate the hash as a key:

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

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

Source: https://habr.com/ru/post/1539456/


All Articles