PHP » Control Structures » if

if (condition) {
   // block 1
} elseif (condition2)
   // block 2
} else { <br>
   // block 3

Chooses a block of code to execute based on a condition.

The block of code inside an if statement is executed if the boolean expression within parentheses evaluates to TRUE. If a boolean operator is not used, anything but zero evaluates to TRUE. "Zero", in this case, also includes empty arrays and empty strings, among other things. Alternative conditions and blocks of code can be added with elseif. A default block of code to execute, if neither the if nor one of the elseif conditions evaluate to true, can be added with else.



$a = 1;
$s = "php";

if ($a == 1) {
   print "\$a is equal to 1<br>";

if ($a) {
   print "\$a is not zero<br>";
} else {
   print "\$a is zero<br>";

if (!$s) {
   print "\$s is an empty string";
} elseif ($s == "hello") {
   print "Hello to you too";
} else {
   print "\$s is: $s";

$a is equal to 1
$a is not zero
$s is: php

The code shows the different combinations in which the if statement can be used.

See Also: