Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

The ALTERNATIVE SYNTAX

All along we have been using a STANDARD syntax - a standard way of setting up commands. We hereby quickly learn alternative ways of applying these commands. Not all of them have alternatives though. Those with an alternative syntax are:

  1. while
  2. for
  3. foreach and
  4. switch.

In all of them you change from STANDARD to ALTERNATIVE Syntax by -

  1. replacing the opening brace ({) of the statement block into a full colon (:) and then
  2. changing the closing brace (}) into either -
  1. endwhile; when you are using the while construct
  2. endfor; when using the for construct
  3. endforeach; when using the foreach and
  4. endswitch; when using the switch construct.

Let's take an example with a while. The STANDARD syntax for the while construct looks like this:

while(condition){
	PHP Statement 1;
	PHP Statement 2;
	PHP Statement ...;
}

To change this so that it makes use of the ALTERNATIVE syntax we will:

a)Change The leading brace into a full colon. - This will cause the code to look like this:

 
while(condition):
	PHP Statement 1;
	PHP Statement 2;
	PHP Statement ...;
}

b) Change the trailing brace into an endwhile - This is because we are using the while construct. Having done that our code will now be:

 
while(condition):
	PHP Statement 1;
	PHP Statement 2;
	PHP Statement ...;
endwhile;

That's It! That's all it takes. Remeber the rules are the same for all the others. You only have to remember to use the right closing statement to match the construct you are using. A quick run of the others is giiven here below:

for()

for(expr1; expr2; expr3):
	PHP Statement 1;
	PHP Statement 2;
	PHP Statement ...;
endfor;

foreach() - Syntax 1

foreach($array as $variable):
	PHP Statement 1;
	PHP Statement 2;
	PHP Statement ...;
endforeach;

foreach() - Syntax 2

foreach($array as $key => $value):
	PHP Statement 1;
	PHP Statement 2;
	PHP Statement ...;
endforeach;

switch()

switch(test expression):
	case: int1
		PHP statement 1;
		PHP statement 2;
		PHP statement 3;
		break;

	case: int2
		PHP statement 1;
		PHP statement 2;
		PHP statement 3;
		break;

	default:
		PHP statement 1;
		PHP statement 2;
		PHP statement 3;
		break;
endswitch;

Well. That kinda' sums it up. So if you have trouble coping with the first type of coding, you can settle for the ALTERNATIVE syntax. Oh yeah... I can see the smile on VB enthusiasts. Thank God there is PHP!

<< The foreach Control Structure | Finally... >>

JamHitz Productions