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 ?>
(PHP 4, PHP 5, PHP 7, PHP 8)
O construtor if
é um dos recursos mais importantes
em muitas linguagens, inclusive no PHP. Permite a
execução condicional de fragmentos de código. O PHP apresenta uma estrutura
if
semelhante a do C:
if (expr) statement
Como descrito na seção sobre
expressões, expressões são avaliadas por seus
valores Booleanos. Se uma expressão for avaliada como true
,
o PHP executará a declaração, e se avaliá-la
como false
- ignorá-la. Mais informações sobre quais valores são avaliados
como false
pode ser encontrada na seção 'Conversão para booleano'
.
O exemplo a seguir exibirá a é maior que b se $a for maior que $b:
<?php
if ($a > $b)
echo "a é maior que b";
?>
Muitas vezes deseja-se que mais de uma declaração seja condicionalmente
executada. É claro que não é necessário envolver cada declaração
em uma cláusula if
. Em vez disso, pode-se agrupar
várias declarações em grupos. Por exemplo, este código
exibirá a é maior que b
se $a for maior que
$b, e atribuirá o valor de
$a em $b:
<?php
if ($a > $b) {
echo "a é maior que b";
$b = $a;
}
?>
A declaração If
pode ser aninhada indefinidamente dentro de outras
declarações if
, fornecendo completa flexibilidade
para execução condicional de várias partes do
programa.
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 ?>
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 lineif ((!empty($someVar))&&($someVar==123)){ echo $someVar;}?>Function someFunc($someVar) will not be called:<?php// $someVar=123; - commented lineif ((!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;}?>
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!
re: #80305Again useful for newbies:if you need to compare a variable with a value, instead of doing<?phpif ($foo == 3) bar();?>do<?phpif (3 == $foo) bar();?>this way, if you forget a =, it will become<?phpif (3 = $foo) bar();?>and PHP will report an error.
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.