Conditionals

Conditionals

if Statement

An if statement takes an expression as an argument:

  • If the expression evaluates to true its associated code block executes.
  • If the expression evaluates to false its associated code block is skipped.
Loading...

The braces {...} are optional when the associated code blocks are only a single line. The above code can be rewritten:

Loading...

else Statement

An else statement can immediately follow the if block. The code block following the else only executes if the if‘s expression evaluates to false. The above code can be rewritten:

Loading...

elseif Statement

Between an if block and an else block, any number of elseif statements and associated code blocks can occur. Each elseif has its own expression to evaluate. The code block associated with the first if or elseif to have a true expression will be the code block to execute. Subsequent elseif blocks will not execute, even if their own expressions are true. The else block will only execute if all if and elseif expressions evaluate false.

Loading...

Note in the above, if the elseif clauses were swapped, then the block where $x < 0 would never execute.

The Ternary Operator

There is a compact version of an if expression called the ternary operator which has the following syntax:

expression ? true value : false value

An example:

Loading...
Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn PHP on Codecademy