MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

Sintaxis Alternativa de Estructuras de Control

PHP ofrece una sintaxis altenativa para alguna de sus estructuras de control; a saber, if, while, for, y switch. En cada caso, la forma básica de la sintaxis alternativa es cambiar abrir-llave por dos puntos (:) y cerrar-llave por endif;, endwhile;, endfor;, or endswitch;, respectivamente.

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

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

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

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

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



add a note add a note User Contributed Notes
Sintaxis Alternativa de Estructuras de Control
08-May-2006 02:51
matheo's example is the classic act of using a hammer to set a screw.  (No offense...)

As programmers, we <b>must</b> become comfortable that the result of a logic-expression <i>is a value</i> just like any other.

Therefore instead of:

<?php
$a
= 1 ;
$b = 2 ;
$is_a_bigger = ($a > $b) ? 1 : 0 ;
echo
$a_is_bigger ;
# returns 0
?>

Use this:

<?php
$a
= 1;
$b = 2;
$a_is_bigger = $a > $b;
...
?>

You read it as "variable $a_is_bigger is set to the result of the comparison of $a to $b".  Compare that to the read-thru of the upper example: "variable $is_a_bigger is set to true if the is-greater comparison of $a to $b is true, and set to false if the comparison is false."  How redundant.  The only thing more redundant is the ever increasingly popular 'duh' logic of today's <i>modern</i> PHP programming:

<?php
   $a
= 1;
  
$b = 2;
   if(
$a > $b )
   {
      
$a_is_bigger = true ;
   }
   else if(
$b >= $a )
   {
      
$a_is_bigger = false ;
   }
?>

8 lines to do what one simple construction can do ... which if we <i>learn to recognize it</i> vastly speeds the reading and appreciation of the purpose of the arbitrary algorithm.

The <b>only constructive criticism</b> that I've heard about the use of both ternary operators and logic-evaluation-direct-assign is that neither of them are easy to debug by adding 'prints' or 'echos' to their interiors.  Point well made.  Yet, if they are as simple as the above examples, it must be argued that the use of 8 lines to accomplish what a single comparison-assignment could do may well have resulted in more potential errors.  (For instance, did I remember to put the '=' in the second comparison as the exact compliment of the first?)

rlynch AT lynchmarks DOT com
davidforest at gmail dot com
19-Oct-2005 06:26
If you need a tidy way to do a lot of condition testing, switch statement will do the job well:

switch (true){

   case ($a>0):
                     //do sth;
                     break;
   case ($b>0):
                     //do sth;
                     break;
   case ($c>0):
                     //do sth;
                     break;
   case ($d>0):
                     //do sth;
                     break;

}
skippy at zuavra dot net
27-Jun-2005 04:32
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.
groundzero at 0845 dot uk dot com
19-May-2005 01:04
Person below...

paul at example dot com didnt say its was a replacement, or exactly the same as the if statement. He just gave a piece of code that, in this case had the same effect.
siebe-tolsma at home dot nl
18-Mar-2004 10:22
As a rection on sttoo, if you use nested if's a bit different they are less likely to cause mistakes:

<?php
$one
= true;
$two = true;

$result = ($one ? "one" : ($two ? "two" : "none"));    // $result is "one"

$one = false;
$result = ($one ? "one" : ($two ? "two" : "none"));    // $result is "two"

$two = false;
$result = ($one ? "one" : ($two ? "two" : "none"));    // $result is "none"

?>
ssttoo at hotmail dot com
05-Dec-2003 05:20
Nested ternary operators can be used, although not a "good programming practice", as it does not promote readability and is prone to errors.

<?php
$one
= true;
$two = true;
$result = ($one) ? "one" : (($two) ? "two" : "none");    // $result is "one"
$result = ($one) ? "one" : ($two) ? "two" : "none";      // $result is "two"
?>
i a m 4 w e b w o r k at hotmail dot com
12-Oct-2003 04:38
Good tutorial on using alternative control structure syntax at:
http://www.onlamp.com/pub/a/php/2001/05/03/php_foundations.html?page=1
paul at example dot com
06-Sep-2003 06:27
There is an other alternative syntax:

<?php
if ($a > 5) {
   echo
"big";
} else {
   echo
"small";
}
?>

can be replaced by:

<?php
echo $a > 5 ? "big" : "small";
?>
matheo at step dot polymtl dot ca
04-Sep-2003 04:37
You can use a short syntax for "if"
$a = (condition) ? value if condition is true : value if condition is false;

<?php
$a
= 1 ;
$b = 2 ;
$is_a_bigger = ($a > $b) ? 1 : 0 ;
echo
$a_is_bigger ;
# returns 0

$a = 2 ;
$b = 1 ;
$is_a_bigger = ($a > $b) ? 1 : 0 ;
echo
$is_a_bigger ;
# returns 1

?>

Citas célebres

Me gusta cuando callas porque estás como ausente...

Pablo Neruda
Poeta chileno
(1904-1973)
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_065.jpg
Contenidos Web

Chiste de... Médicos
Conoce a su marido

- Y dígame, ¿su marido también habla consigo mismo cuando está solo?

- No lo sé, nunca he estado con él cuando estaba solo.
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_024.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0497.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail

Warning: array_rand(): First argument has to be an array in /var/www/html/contenidos/efemerides.php on line 14
Sucedió el...

31 de agosto de

Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid