Web20 University

PHP if Statements

Get up to 65% Off Hosting with FREE SSL & FREE Domains!

* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.

An if statement in PHP is a fundamental programming construct used for conditional execution of code. It allows you to execute a block of code only if a specified condition is true. If the condition is false, the block of code will be skipped.

Here is the basic syntax of an if statement in PHP:

if (condition) {
    // Code to be executed if the condition is true
}

The condition within the parentheses can be any expression that evaluates to a boolean value (i.e., true or false). If the condition is true, the code within the curly braces will be executed.

Here’s an example with a simple condition:

$number = 5;

if ($number > 0) {
    echo "The number is positive.";
}

In this example, the if statement checks if the value of $number is greater than 0. If the condition is true, it will output “The number is positive.”

For more complex conditions, you can use else and elseif clauses along with the if statement:

if (condition1) {
    // Code to be executed if condition1 is true
} elseif (condition2) {
    // Code to be executed if condition1 is false and condition2 is true
} else {
    // Code to be executed if both condition1 and condition2 are false
}

You can find more information and examples on how if statements work in PHP from the following official PHP documentation references:

Get up to 65% Off Hosting with FREE SSL & FREE Domains!