Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP endswitch; - Is this normally practiced?

I was reading some switch statements and noticed one using endswitch;. Why or why not should one use this? Is it even necessary?

like image 638
Strawberry Avatar asked Nov 28 '22 19:11

Strawberry


2 Answers

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.

like image 127
Sebastian Paaske Tørholm Avatar answered Dec 10 '22 07:12

Sebastian Paaske Tørholm


+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.

like image 37
Ardee Aram Avatar answered Dec 10 '22 09:12

Ardee Aram