Apr 20, 2008

PHP Control Statements

PHP Control Statements

if, elseif, else

if ( )
{
}
elseif ( )
{
}
else
{
}

switch

switch ( )
{
case condition1
        break;
case condition2
   break;
}

while

Syntax:

while (condition)
{
}

do

do
{
} while (condition)

for

Example use of the for statement:

<?php
for ( $n = 1; $n < 10; $n++)
{
   echo "$n<BR>";
}

?>

foreach

Versions of PHP prior to version 4 do not support the foreach statement. The following code should list the contents of the array.

<?php
$tree = array("trunk", "branches", "leaves");
foreach ($tree as $part)
{
  echo "Tree part: $part ";
}
?>

break

Is used to end the execution of a for, switch, or while statement

continue

This statement is used to skip the rest of the current loop.

<?php
for ( $n = 1; $n < 10; $n++)
{
   echo "$n<BR>";
        if ($n == 5) continue;
  echo "This statement is skipped when $n = 5.<BR>";
}
?>

The continue statement can be given an optional parameter such as "continue 2" telling it how many levels of loops to skip

No comments:

Post a Comment

Popular Posts