PHP.nl

Alternative syntax for control structures

Alternative syntax for control structures

PHP offers an alternative syntax for some of its control structures; namely, , , , , and . In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to , , , , or , respectively.

`ifwhileforforeachswitchendif;endwhile;endfor;endforeach;``endswitch;````php

A is equal to 5





  In the above example, the HTML block "A is equal to 5" is nested within an
   statement written in the alternative syntax.  The
  HTML block would be displayed only if  is equal to 5.
 `if``$a`


  The alternative syntax applies to  and
   as well.  The following is an
   structure with  and
   in the alternative format:
  
 `else``elseif``if``elseif``else````php
<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>

Opmerking: > Mixing syntaxes in the same control block is not supported.

Waarschuwing: > Any output (including whitespace) between a statement and the first will result in a syntax error. For example, this is invalid: switch``case

<?php switch ($foo): ?>
    <?php case 1: ?>
    // ...
<?php endswitch; ?>

Whereas this is valid, as the trailing newline after the statement is considered part of the closing and hence nothing is output between the and : switch``?&gt;``switch``case

<?php switch ($foo): ?>
<?php case 1: ?>
    ...
<?php endswitch; ?>

See also , , and for further examples. whileforif