PHP 8.3.21 Released!

if

(PHP 4, PHP 5, PHP 7, PHP 8)

La instrucción if es una de las más importantes instrucciones de todos los lenguajes, PHP incluido. Permite la ejecución condicional de una parte de código. Las funcionalidades de la instrucción if son las mismas en PHP que en C :

if (expression)
  commandes

Como se ha visto en el párrafo dedicado a las expressions, expression es convertida en su valor booléen. Si la expression vale true, PHP ejecutará la instruction y si vale false, la instrucción será ignorada. Más detalles sobre los valores que valen false están disponibles en la sección Conversión en booléen.

El siguiente ejemplo muestra la frase a es más grande que b si $a es más grande que $b :

<?php
if ($a > $b)
echo
"a es más grande que b";
?>

A menudo, se desea que varias instrucciones sean ejecutadas después de un desvío condicional. Por supuesto, no es obligatorio repetir la instrucción condicional if tantas veces como instrucciones se tengan que ejecutar. En su lugar, se pueden agrupar todas las instrucciones en un bloque. El siguiente ejemplo muestra a es más grande que b, si $a es más grande que $b, y luego asigna el valor de $a a la variable $b :

<?php
if ($a > $b) {
echo
"a es más grande que b";
$b = $a;
}
?>

Se pueden anidar indefinidamente instrucciones if dentro de otras instrucciones if, lo que permite una gran flexibilidad en la ejecución de una parte de código según un gran número de condiciones.

add a note

User Contributed Notes 5 notes

up
190
robk
11 years ago
easy way to execute conditional html / javascript / css / other language code with php if else:

<?php if (condition): ?>

html code to run if condition is true

<?php else: ?>

html code to run if condition is false

<?php endif ?>
up
8
georgy dot moshkin at techsponsor dot io
9 months ago
Left-to-right evaluation of && operators has one useful feature: evaluation stops after first "false" operand is encountered.

This feature can be useful for creating following construction:

$someVar==123 is not evaluated, so there will be no warnings such as "Undefined variable $someVar":
<?php
// $someVar=123; - commented line
if ((!empty($someVar))&&($someVar==123))
{
echo
$someVar;
}
?>

Function someFunc($someVar) will not be called:
<?php
// $someVar=123; - commented line
if ((!empty($someVar))&&(someFunc($someVar)))
{
echo
$someVar;
}
?>

This will give "Warning: Undefined variable $someVar" error. Order matters:
<?php
// $someVar=123;
if ((someFunc($someVar))&&(!empty($someVar)))
{
echo
$someVar;
}
?>
up
49
techguy14 at gmail dot com
14 years ago
You can have 'nested' if statements withing a single if statement, using additional parenthesis.
For example, instead of having:

<?php
if( $a == 1 || $a == 2 ) {
if(
$b == 3 || $b == 4 ) {
if(
$c == 5 || $ d == 6 ) {
//Do something here.
}
}
}
?>

You could just simply do this:

<?php
if( ($a==1 || $a==2) && ($b==3 || $b==4) && ($c==5 || $c==6) ) {
//do that something here.
}
?>

Hope this helps!
up
24
grawity at gmail dot com
17 years ago
re: #80305

Again useful for newbies:

if you need to compare a variable with a value, instead of doing

<?php
if ($foo == 3) bar();
?>

do

<?php
if (3 == $foo) bar();
?>

this way, if you forget a =, it will become

<?php
if (3 = $foo) bar();
?>

and PHP will report an error.
up
16
Christian L.
14 years ago
An other way for controls is the ternary operator (see Comparison Operators) that can be used as follows:

<?php
$v
= 1;

$r = (1 == $v) ? 'Yes' : 'No'; // $r is set to 'Yes'
$r = (3 == $v) ? 'Yes' : 'No'; // $r is set to 'No'

echo (1 == $v) ? 'Yes' : 'No'; // 'Yes' will be printed

// and since PHP 5.3
$v = 'My Value';
$r = ($v) ?: 'No Value'; // $r is set to 'My Value' because $v is evaluated to TRUE

$v = '';
echo (
$v) ?: 'No Value'; // 'No Value' will be printed because $v is evaluated to FALSE
?>

Parentheses can be left out in all examples above.
To Top