php – How to simplify multiple else if?

Question:

There is dynamic data from the user, which must be checked on the server for occurrence in a particular range and, depending on this, display a different result.

The only thing that comes to my mind is (example conditional):

if($var < 1000) {
    do one
}
else if ($var < 2000) {
    do two
}
else if ($var < 3000) {
    do three
}
.... и т.д.

Can you tell me how to simplify this design?

Answer:

Since the author, for some reason, stubbornly refuses to admit what kind of result he needs to display, he will have to fantasize.

If we just need to display some text, we will need such knowledge from the elementary school course as division and rounding.

$results = [
    "Герой пионерского лагеря",
    "Дважды герой пионерского лагеря",
    "Многократный призер куличиков и совочка",
]
$place = floor($var / 1000);
echo $results[$place] ?? 'Завхоз по наградам';
Scroll to Top