In programming, conditional statements allow different actions to occur based on varying circumstances. By using conditions, PHP enables you to control the flow of your code execution.
PHP Conditional Statements
PHP provides several options for conditional statements to handle multiple scenarios:
if
statement – Executes a block of code if a specific condition is true.if...else
statement – Executes one block of code if the condition is true and an alternative block if the condition is false.if...elseif...else
statement – Allows you to handle more than two conditions by executing different blocks of code depending on the situation.switch
statement – Evaluates a variable and executes one block of code based on the matching case.
PHP – The if
Statement
The if
statement runs a block of code only when its condition evaluates to true.
Syntax
if (condition) { // Code to execute if the condition evaluates to true }
Example 1
Output “Ride safe!” if 100
is greater than 50
:
if (100 > 50) { echo "Ride safe!"; }
Example 2
Using a variable to decide what message to display. Output “Enjoy your motorcycle ride!” if $cc
(cubic capacity) is below 500
:
$cc = 400; if ($cc < 500) { echo "Enjoy your motorcycle ride!"; }