Which is the better and fastest methods : if or switch ?
if(x==1){
echo "hi";
} else if (x==2){
echo "bye";
}
switch(x){
case 1
...
break;
default;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your first example is simply wrong. You need
elseifinstead of justelse.If you use
if..elseif...orswitchis mainly a matter of preference. The performance is the same.However, if all your conditions are of the type
x == valuewithxbeing the same in every condition,switchusually makes sense. I’d also only useswitchif there are more than e.g. two conditions.A case where
switchactually gives you a performance advantage is if the variable part is a function call:Then
some_func()is only called once while withit would be called twice – including possible side-effects of the function call happening twice. However, you could always use
$res = some_func();and then use$resin yourifconditions – so you can avoid this problem alltogether.A case where you cannot use switch at all is when you have more complex conditions –
switchonly works forx == ywithybeing a constant value.