I'm in a dilemma. Which is best to use and why.. switch or if?
switch ($x)
{
case 1:
//mysql query
//echo something
break;
case 2:
//mysql query
//echo something
break;
}
...
if ($x == 1) {
//mysql query
//echo something
}
if ($x == 2) {
//mysql query
//echo something
}
They have different meanings.
The first example will stop when the condition is met.
The second will test $x
twice.
You may want to make your second if
an else if
. This will mean the block will be skipped as soon as one condition evaluates to true.
But if you are wondering which one is fastest, you should instead think which one most effectively communicates what I want to do. They will both most probably end up as conditional jumps in the target architecture.
Premature optimisation... (you know the rest :P )
Switch is better when there are more than two choices. It's mostly for code readability and maintainability rather than performance.
As others have pointed out, your examples aren't equivalent, however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With