Programs need to make decisions. The if statement runs a block of code only when a condition is true.
<?php
$age = 20;
if ($age >= 18) {
echo "You can vote.";
}
You can vote.
The condition goes inside the brackets. If it is true, the code inside the curly braces runs. If it is false, PHP skips it.
<?php
$age = 15;
if ($age >= 18) {
echo "You can vote.";
}
echo "Done.";
Done.
What a condition is
A condition is any expression that PHP can treat as true or false. Comparisons are the most common kind.
<?php
$stock = 0;
if ($stock === 0) {
echo "Sold out";
}
Sold out
Booleans work directly
If a variable already holds true or false, you do not need a comparison.
<?php
$isLoggedIn = true;
if ($isLoggedIn) {
echo "Welcome back!";
}
Welcome back!
Use ! to run code when something is not true.
<?php
$isLoggedIn = false;
if (!$isLoggedIn) {
echo "Please log in.";
}
Please log in.
Several statements in the block
<?php
$total = 1200;
if ($total > 1000) {
$discount = $total * 0.1;
echo "Discount: $discount\n";
echo "Free shipping applied.";
}
Discount: 120
Free shipping applied.
Combine conditions
<?php
$age = 25;
$hasId = true;
if ($age >= 18 && $hasId) {
echo "Entry allowed";
}
Entry allowed
One equals sign
if ($score = 10) assigns 10 to $score and is always true. You want == or, better, ===. See Comparison Operators.Exercise: password length
Write an if that prints Too short when $password has fewer than 8 characters.
Show a possible solution
<?php
$password = "abc123";
if (strlen($password) < 8) {
echo "Too short";
}
Too short