0

There are data from the user that I need to check for membership in a particular range, and depending on this output a different result. I use this method:

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

But it looks unprofessional. How can I optimize this code? /without 'switch' - it's almost the same/

humster_spb
  • 193
  • 1
  • 2
  • 8

2 Answers2

2

Looks fine to me:

  1. It's readable.

  2. It's unlikely to be a performance bottleneck.

Don't overthink this. You could probably massage the whole thing into a table of functions keyed by ranges, but why obfuscate what is clear and simple?

Don't use a chain of ternary conditional operators since, for some reason, the PHP folk decided to fiddle around with the associativity of that operator cf. C, C++, and Java.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

I guess it depends on the logic inside each if - else block. If it is just returning, or calling a method for example, you could do the following:

if ($var < 1000) return 1;
if ($var < 2000) return 2;
if ($var < 3000) return 3;

If the logic inside each condition is more than one operation, you could move it to a function and simple call the relevent function.

To be honest, what you have is fine. As long as it is clean and readable. You should only start worrying about cleanliness when they become more nested.

OllyBarca
  • 1,501
  • 1
  • 18
  • 35