Reputation: 45
I only have one case in switch statement
switch ($coreName) {
case 'stock':
$result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
break;
}
My question is this a good practice or shall I use an if statement for this? Any performance differences or anything?
Upvotes: 1
Views: 3733
Reputation: 42915
Nothing speaks against this from a technical point of view.
So the question to answer is: why did you implement a switch
statement instead of an if
conditional?
I'd say the default should be an "normal" if
condition, unless special reasons point to a switch
instead. The two primary reasons might be:
Especially the first case should be considered here. If it might become necessary to extend the handling, then certainly using a switch
right away is a good practice.
Upvotes: 3
Reputation: 11693
Use if else Only when :
1. you have only 2 or more conditions OR You have multiple conditions in single if else.
And use switch when
1. You have to compare `ONE` variable value against multiple.
In your case if else is better
Upvotes: 2
Reputation: 15609
If you go to phpBench.com and scroll down to see the results between if
and case
, you can see that using an if
statement is slightly faster, but the results aren't too different. (Screenshot below)
You may as well use an if
as it is easier to read, less code and is still faster (even by only a tiny amount).
if($corename === "stock") {
$result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
}
case
should only be used when you compare multiple values rather than just one. This is the same as using elseif
. Using if
is the most suited for this specifically.
Upvotes: 1
Reputation: 813
Why not simply do a simple if, like this :
if($coreName == 'stock')
{
$result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
}
Hope this helps.
Upvotes: 0