Reputation: 1149
This is a quick one. Is there a way to compare a given value to a multidimensional array of preset rules, without looping through our rules?
I'll give you an example. Let's say we are evaluating students from 1 to 10. And we want to assign a performance assessment with a few words. So we'd have ranges of marks and what they represent, for example:
$evaluation = array(
array('from' => 1, 'to' => 3, 'comment' => 'Stop watching TV'),
array('from' => 4, 'to' => 6, 'comment' => 'Keep trying'),
array('from' => 7, 'to' => 8, 'comment' => 'Almost there'),
array('from' => 9, 'to' => 10, 'comment' => 'EMC2')
);
A student got 8, so we'd do:
$grade = 8;
foreach($evaluations as $evaluation) {
if($grade >= $evaluation['from'] && $grade <= $evaluation['to']) {
echo $evaluation['comment'];
}
}
Which I guess is fine. But is there a more neater way to do this? Perhaps a built-in PHP function that would be faster than looping through our set of rules?
Thanks.
Upvotes: 1
Views: 70
Reputation: 11447
Think you're over thinking the array a bit, you could key by max value in each range, it's a little less data, and less to evaluate, but in all honesty it seems like a micro optimisation
$evaluation = array(
3 => 'Stop watching TV',
6 => 'Keep trying',
8 => 'Almost there',
10 => 'EMC2'
);
$grade = 8;
foreach ($evaluation as $limit => $comment) {
if ($limit < $grade) continue;
break;
}
echo $comment;
Upvotes: 1
Reputation: 46785
A switch statement would be slightly faster but since you are dealing with a 4-element array, almost anything will do.
If you unroll the loop by using a switch
statement, you reduce the number of expressions that need to be evaluated since in your loop you need to make a greater than and a less than comparison. Using the switch
, you need only one comparison.
There are other PHP functions like array_filter
and array_reduce
that may lead to the same result if you define the correct callback function, but what you have right now may be as good as anything else.
Upvotes: 2