Sintaxis alternativa de estructuras de control

(PHP 4, PHP 5)

PHP ofrece una sintaxis alternativa para algunas de sus estructuras de control; a saber: if, while, for, foreach, y switch. En cada caso, la forma básica de la sintaxis alternativa es cambiar el corchete de apertura por dos puntos (:) y el corchete de cierre por endif;, endwhile;, endfor;, endforeach;, o endswitch;, respectivamente.

<?php if ($a == 5): ?>
A es igual a 5
<?php endif; ?>

En el ejemplo anterior, el bloque HTML "A es igual a 5" se anida dentro de una sentencia if escrita en la sintaxis alternativa. El bloque HTML se mostraría solamente si $a es igual a 5.

La sintaxis alternativa también se aplica a else y elseif. El siguiente es una estructura if con elseif y else en el formato alternativo:

<?php
if ($a == 5):
    echo 
"a igual 5";
    echo 
"...";
elseif (
$a == 6):
    echo 
"a igual 6";
    echo 
"!!!";
else:
    echo 
"a no es 5 ni 6";
endif;
?>

Nota:

No se admite la mezcla de sintaxis en el mismo bloque de control.

Advertencia

Cualquier salida (incluyendo espacios en blanco) entre una sentencia switch y el primer case resultará en un error de sintaxis. Por ejemplo, esto es válido:

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

Mientras que esto es válido, ya que la nueva línea al final después de la sentencia switch es considerada como parte del ?> de cierre, no generando nada entre el switch y el case:

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

Véase también while, for e if para más ejemplos.

add a note add a note

User Contributed Notes 8 notes

up
55
flyingmana
5 years ago
It seems to me, that many people think that

<?php if ($a == 5): ?>
A ist gleich 5
<?php endif; ?>

is only with alternate syntax possible, but

<?php if ($a == 5){ ?>
A ist gleich 5
<?php }; ?>

is also possible.

alternate syntax makes the code only clearer and easyer to read
up
39
temec987 at gmail dot com
3 years ago
A simple alternative to an if statement, which is almost like a ternary operator, is the use of AND. Consider the following:

<?php
     $value
= 'Jesus';

    
// This is a simple if statement
    
if( isset( $value ) )
     {
          print
$value;
     }

     print
'<br />';

    
// This is an alternative
    
isset( $value ) AND print( $value );
?>

This does not work with echo() for some reason. I find this extremely useful!
up
9
v14t at gmx dot com
6 months ago
isset( $value ) AND print( $value );

the reason why it doesn't work with echo, it's because echo does not return anything, while print _always_ returns 1, which is considered true in the expression
up
11
skippy at zuavra dot net
9 years ago
If it needs saying, this alternative syntax is excellent for improving legibility (for both PHP and HTML!) in situations where you have a mix of them.

Interface templates are very often in need of this, especially since the PHP code in them is usually written by one person (who is more of a programmer) and the HTML gets modified by another person (who is more of a web designer). Clear separation in such cases is extremely useful.

See the default templates that come with WordPress 1.5+ (www.wordpress.org) for practical and smart examples of this alternative syntax.
up
10
jeremia at gmx dot at
6 years ago
If you wan't to use the alternative syntax for switch statements this won't work:

<div>
<?php switch($variable): ?>
<?php
case 1: ?>
<div>
Newspage
</div>
<?php break;?>
<?php
case 2: ?>
</div>
Forum
<div>
<?php break;?>
<?php
endswitch;?>
</div>

Instead you have to workaround like this:

<div>
<?php switch($variable):
case
1: ?>
<div>
Newspage
</div>
<?php break;?>
<?php
case 2: ?>
</div>
Forum
<div>
<?php break;?>
<?php
endswitch;?>
</div>
up
4
ej at iconcept dot fo
5 years ago
if statement in 1 line
<?php
$hour
= 11;

print
$foo = ($hour < 12) ? "Good morning!" : "Good afternoon!";

?>
return Good morning!
up
0
timeroot dot alex at gmail dot com
10 months ago
The reason for the "workaround" jeremiah mentioned, in the case of the switch statement, can be understood as follows; in any place where you can have an echo statement (an if block, a switch's case, whatever), that's where you can have the raw HTML. In PHP this basically gets handled just like that -- like an echo statement.

In between a switch and a case, though, you can't echo anything. By placing the switch and the case in two separate blocks of PHP, with a raw HTML newline echo'ed in between them, PHP basically had to try to find where that statement would be. And it can't be there, hence the difficulty.
up
-4
josh at qaribou dot com
7 months ago
The reason temec987's approach of using boolean operators as an alternative to control structures won't work for an 'echo' is because the result of evaluating the expression will always be a boolean.

Other languages (e.g. ruby) are much better suited to this approach, as the expression evaluated will be the resultant value, e.g.:
5 && 4

In ruby, this would be 4, but in PHP, this would be true (type-juggled equivalent is 1), which isn't useful for anything but further binary logic.

You can still use logical operators as conditionals, but only for executing logic, not for getting a value back, e.g.:
<?php
defined
('USER_CAN_EXECUTE') or die('Access denied.');
?>

is a nice one to use for access control, or say you want to put in a quick check that your object has all the data loaded it needs to call a webservice (functions are just examples):
<?php
$this
->readyForService() and $this->postData('http://endpoint.com');
?>

What you can't use them for is something like this:
<?php
echo (strlen($mystring) > 5) and $mystring;
?>

instead, you'd use ternaries for that:
<?php
echo (strlen($mystring) > 5) ? $mystring : null;
?>
To Top