note 102305 added to control-structures.if

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Como dijo Christian L. , los operadores ternarios pueden ser muy útiles para reducir el código.
 El operador ternario evalúa una condición y retorna un valor dependiendo si la condición es verdadera (true) o falsa (false).
 Por ejemplo, este if

<?php
if (condición) {
$variable = 'valor-cuando-es-verdadera';
} else {
$variable = 'valor-cuando-es-falsa';
}
?>

Utilizando el operador ternario quedaría de esta manera:

<?php
$variable = (condición) ? 'valor-cuando-es-verdadera' : 'valor-cuando-es-falsa';
?>

Otro ejemplo:

<?php
//Declaramos una variable cualquiera para usar en el if
$foo = 2;

if ($foo == 2) {
$mensaje = 'Foo es igual a 2';
} else {
$mensaje = 'Foo no es igual a 2';
}
echo $mensaje;
?>

Aplicando el operador ternario:

<?php
$foo = 2;

$mensaje = ($foo == 2) ? 'Foo es igual a 2' : 'Foo no es igual a 2';
echo $mensaje;
?>

Más simplificado:

<?php
$foo = 2;
echo ($foo == 2) ? 'Foo es igual a 2' : 'Foo no es igual a 2';
?>
----
Server IP: 69.147.83.197
Probable Submitter: 186.108.181.130
----
Manual Page -- http://www.php.net/manual/en/control-structures.if.php
Edit        -- https://master.php.net/note/edit/102305
Del: integrated  -- https://master.php.net/note/delete/102305/integrated
Del: useless     -- https://master.php.net/note/delete/102305/useless
Del: bad code    -- https://master.php.net/note/delete/102305/bad+code
Del: spam        -- https://master.php.net/note/delete/102305/spam
Del: non-english -- https://master.php.net/note/delete/102305/non-english
Del: in docs     -- https://master.php.net/note/delete/102305/in+docs
Del: other reasons-- https://master.php.net/note/delete/102305
Reject      -- https://master.php.net/note/reject/102305
Search      -- https://master.php.net/manage/user-notes.php
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.