I was reading some switch statements and noticed one using endswitch;
. Why or why not should one use this? Is it even necessary?
It is used if you use the alternative syntax for control structures.
Thus you could either choose
switch ($var) {
case 1:
echo "Hello!\n";
break;
case 2:
echo "Goodbye!\n";
break;
default:
echo "I only understand 1 and 2.\n";
}
or
switch ($var):
case 1:
echo "Hello!\n";
break;
case 2:
echo "Goodbye!\n";
break;
default:
echo "I only understand 1 and 2.\n";
endswitch;
They are functionally identical, and merely provided as syntactic sugar.
+1 TO Amber. The alternative syntax is no doubt more readable, especially when inserting control structures among HTML. And yes, the accepted coding standards varies on the organization. In our case, we use the if(): endif in templates, and if(){} in logic and backend portion of the code. Observe the neatness of the code, including the indentation:
<?php if($number %2 != 0):?>
<p>I guess the number is odd</p>
<?php else:?>
<p>I guess the number is even</p>
<?php endif?>
In this case, you don't even need that pesky semicolon in the end.
Just to compare, here is the "unalternative" (or original) way:
<?php if($number %2 != 0) {?>
<p>I guess the number is odd</p>
<?php } else {?>
<p>I guess the number is even</p>
<?php }?>
Observe the aesthetically-disturbing curly braces all over the code. The first style fits better with HTML tags.
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