if

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

Конструкция if является одной из наиболее важных во многих языках программирования, в том числе и PHP. Она предоставляет возможность условного выполнения фрагментов кода. Структура if реализована в PHP по аналогии с языком C:

if (выражение)
  инструкция

Как описано в разделе про выражения, выражение вычисляется в булево значение. Если выражение принимает значение true, PHP выполнит инструкцию, а если оно принимает значение false - проигнорирует. Информацию о том, какие значения считаются равными значению false, можно найти в разделе 'Преобразование в булев тип'.

Следующий пример выведет a больше b, если значение переменной $a больше, чем $b:

<?php
if ($a > $b)
echo
"a больше b";
?>

Часто необходимо, чтобы условно выполнялось более одной инструкции. Разумеется, для этого нет необходимости помещать каждую инструкцию в if. Вместо этого можно объединить несколько инструкций в блок. Например, следующий код выведет a больше b, если значение переменной $a больше, чем $b, а затем присвоит значение переменной $a переменной $b:

<?php
if ($a > $b) {
echo
"a больше b";
$b = $a;
}
?>

Инструкции if могут быть бесконечно вложены в другие инструкции if, что даёт большую гибкость в организации условного выполнения различных частей программы.

add a note

User Contributed Notes 7 notes

up
184
robk
10 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
31
grawity at gmail dot com
15 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
24
techguy14 at gmail dot com
12 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
19
Christian L.
12 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.
up
-10
Donny Nyamweya
12 years ago
In addition to the traditional syntax for if (condition) action;
I am fond of the ternary operator that does the same thing, but with fewer words and code to type:

(condition ? action_if_true: action_if_false;)

example

(x > y? 'Passed the test' : 'Failed the test')
up
-16
cole dot trumbo at nospamthnx dot gmail dot com
5 years ago
Any variables defined inside the if block will be available outside the block. Remember that the if doesn't have its own scope.

<?php
$bool
= true;
if (
$bool) {
   
$hi = 'Hello to all people!';
}
echo
$hi;
?>

It will print 'Hello to all people!'

On the other hand, this will have no output:

<?php
if (false) {
   
$hi = 'Hello to all people!';
}
echo
$hi;
?>
up
-4
chiel at comfitech dot nl
1 month ago
Note that the IF statement does not always evaluates all expressions. In the next example the second expression will not be evaluated causing our function not to run. Because the result is already TRUE and the rest of the expressions are behind the OR operator they will be ignored.

<?php

$a
= 0;

if (
true || $a = important_function() ) echo $a;

function
important_function(){
 
// Do very important stuff here.
 
return 1;
}

?>
To Top