PHP endswitch; - Is this normally practiced?

12,686

Solution 1

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.

Solution 2

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

Solution 3

I've never used the switch variant, but for if statements or for statements it can be handy in templates.

But It's mostly a matter of taste.

Solution 4

The alternative syntax is very nice in template files.

Share:
12,686
Strawberry
Author by

Strawberry

I want to learn industry practices and apply them to my projects to make myself successful

Updated on August 19, 2022

Comments

  • Strawberry
    Strawberry over 1 year

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