The if statement
Learn how to check a condition with if and the code block.
The if statement
An if statement runs a code block when a condition is true. The condition goes in parentheses; when it is true the code between the curly braces runs, when false it is skipped.
For example, a cafe can apply a discount when the daily order count is greater than 10: if ($cups > 10) { echo 'discount'; }. This lets the program make a decision on its own.
Code block and condition
In an if statement the condition is always a boolean expression: a comparison that returns true or false. The part between the curly braces { } is called the code block.
The block can hold several statements; each ends with a semicolon. When the condition is false the whole block is skipped and the program continues with the next statement.
Exercise Write a temperature warning
The $temperature variable is already declared. Write an if with the condition $temperature > 30; when true, print 'hot' with echo. Do not use else.
Show example solution
For the temperature, write if ($temperature > 30) { echo 'hot'; }.
Example solution:
<?php
$temperature = 32;
// Temperature check
if ($temperature > 30) {
echo 'hot';
}
Test yourself
-
What is the output of $cups = 12; if ($cups > 10) { echo 'discount'; }?
$cups = 12; if ($cups > 10) { echo 'discount'; }- discount
- 12
- true
- 1
Show answer
discount — Correct. 12 is greater than 10, so the block runs and prints 'discount'.
-
Write the if keyword
$cups = 12; ____ ($cups > 10) { echo 'discount'; }Show answer
$cups = 12; if ($cups > 10) { echo 'discount'; } -
Match the if parts
- if
- Condition keyword
- ( )
- Condition parens
- { }
- Code block
- true / false
- Boolean value