tags:

views:

132

answers:

5

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

+4  A: 

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.

Sebastian P.
A: 

The usual systax for switch statements in c-style languages is like this:

switch($foo) {
    case 1:  foobar();
             break;
    case 2:  something();
             break;
    case 3:  whatever();
             break;
    default: anything();
}

Never saw "endswitch" in actual production code.

I'd recommend sticking to the accepted coding standards to keep your code readable and maintainable.

Techpriester
"The accepted coding standards" according to whom? If anything, the alternate syntax is far *more* readable.
Amber
+1  A: 

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.

Ikke
+1  A: 

The alternative syntax is very nice in template files.

WishCow