if

(PHP 4, PHP 5, PHP 7)

The if construct is one of the most important
features of many languages, PHP included. It allows for
conditional execution of code fragments. PHP features an
if structure that is similar to that of C:

if (expr)
statement

As described in the section about
expressions, expression is evaluated to its
Boolean value. If expression evaluates to TRUE,
PHP will execute statement, and if it evaluates
to FALSE - it'll ignore it. More information about what values evaluate
to FALSE can be found in the 'Converting to boolean'
section.

The following example would display a is bigger
than b if $a is bigger
than $b:

<?phpif ($a > $b) echo "a is bigger than b";?>

Often you'd want to have more than one statement to be executed
conditionally. Of course, there's no need to wrap each statement
with an if clause. Instead, you can group
several statements into a statement group. For example, this code
would display a is bigger than b
if $a is bigger than
$b, and would then assign the value of
$a into $b:

<?phpif ($a > $b) { echo "a is bigger than b";$b = $a;}?>

If statements can be nested infinitely within other
if statements, which provides you with complete
flexibility for conditional execution of the various parts of your
program.

<?php// Alphabetical Comparison$a="brian";$b="zebra"; if ($a < $b){ echo $a." is before ".$b." in the alphabet"; } else{ echo $a." is after ".$b." in the alphabet"; }// Result : brian is before zebra in the alphabet?>

When using if statements without the curly braces, remember than only one statement will be executed as part of that condition. If you want to place multiple statements you must use curly braces, and not just put them on the same line.

<?php

if (1==0) echo "Test 1."; echo "Test 2";

?>

Whereas some people would expect nothing to be displayed, this piece of code will show: "Test 2".

This has got the better part of my last 2 hours, so I'm putting it here, maybe it will save someone some time.

I had a

if (function1() && function2())

statement. Before returning true or false, function1() and function2() had to output some text. The trick is that, if function1() returns false, function2() is not called at all. It seems I should have known that, but it slipped my mind.

You should put your arguments in order by *least* likely to be true. That way if php is going to be able to quit checking, it will happen sooner rather than later, and your script will run (what amounts to unnoticeably) faster.

At least, that makes the most sense to me, but I don't claim omniscience.

Note that safe type checking (using === and !== instead of == and !=) is in general somewhat faster. When you're using non-safe type checking and a conversion is really needed for checking, safe type checking is considerably faster.