Skip to content

PHP Tutorial Conditional Statements

PHP if Statement

Lesson 81 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Programs need to make decisions. The if statement runs a block of code only when a condition is true.

index.php
PHP
<?php
$age = 20;

if ($age >= 18) {
    echo "You can vote.";
}
Output
OUTPUT
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.

index.php
PHP
<?php
$age = 15;

if ($age >= 18) {
    echo "You can vote.";
}

echo "Done.";
Output
OUTPUT
Done.

What a condition is

A condition is any expression that PHP can treat as true or false. Comparisons are the most common kind.

index.php
PHP
<?php
$stock = 0;

if ($stock === 0) {
    echo "Sold out";
}
Output
OUTPUT
Sold out

Booleans work directly

If a variable already holds true or false, you do not need a comparison.

index.php
PHP
<?php
$isLoggedIn = true;

if ($isLoggedIn) {
    echo "Welcome back!";
}
Output
OUTPUT
Welcome back!

Use ! to run code when something is not true.

index.php
PHP
<?php
$isLoggedIn = false;

if (!$isLoggedIn) {
    echo "Please log in.";
}
Output
OUTPUT
Please log in.

Several statements in the block

index.php
PHP
<?php
$total = 1200;

if ($total > 1000) {
    $discount = $total * 0.1;
    echo "Discount: $discount\n";
    echo "Free shipping applied.";
}
Output
OUTPUT
Discount: 120
Free shipping applied.

Combine conditions

index.php
PHP
<?php
$age = 25;
$hasId = true;

if ($age >= 18 && $hasId) {
    echo "Entry allowed";
}
Output
OUTPUT
Entry allowed
warning
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
index.php
PHP
<?php
$password = "abc123";

if (strlen($password) < 8) {
    echo "Too short";
}
Output
OUTPUT
Too short