Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The if statement is a fundamental control flow structure in PHP that dictates the conditional execution of a code block based on the evaluation of a specified expression. If the expression evaluates to true, the nested statement or code block is executed; if it evaluates to false, the execution bypasses the block.

Standard Syntax

PHP utilizes C-style syntax for standard control structures, enclosing the conditional expression in parentheses and the executable block in curly braces.
if (expression) {
    // statement(s) to execute if expression evaluates to true
}
If only a single statement is to be executed, the curly braces can technically be omitted. However, modern PHP coding standards (such as PER/PSR-12) mandate the use of curly braces for all control structures to prevent scope-related bugs during maintenance.
// Valid, but discouraged by coding standards
if (expression)
    statement;

Expression Evaluation and Type Juggling

The expression inside the if statement does not need to be a strict boolean type. PHP utilizes implicit type casting (type juggling) to evaluate the expression in a boolean context. The following values are implicitly cast to false (often referred to as “falsy” values):
  • The boolean false itself
  • The integer 0 (zero)
  • The float 0.0 (zero)
  • The empty string "", and the string "0"
  • An array with zero elements []
  • The special type NULL (including unset variables)
  • SimpleXML objects created from empty tags
Any value not strictly matching the list above evaluates to true.

Branching: else and elseif

The if statement can be extended using else to define a fallback block when the initial expression evaluates to false, and elseif to evaluate subsequent conditions.
if (expression1) {
    // executed if expression1 is true
} elseif (expression2) {
    // executed if expression1 is false and expression2 is true
} else {
    // executed if all preceding expressions are false
}
Note: PHP accepts both elseif (single word) and else if (two words) when using curly braces. The parser treats them identically in this context.

Alternative Syntax

PHP provides an alternative syntax for control structures, which is primarily utilized within view templates mixed with HTML. This syntax replaces the opening curly brace with a colon (:) and the closing curly brace with the endif; keyword.
if (expression1):
    // statement(s)
elseif (expression2):
    // statement(s)
else:
    // statement(s)
endif;
Crucial Distinction: When using the alternative syntax, you must use the single-word elseif. Using the two-word else if with the colon syntax will result in a parse error.
Master PHP with Deep Grasping Methodology!Learn More