PHP Tutorial menu

PHP Conditions

Conditions let your program choose what to do, for example show "Pass" or "Fail" depending on marks.

Comparison Operators

A comparison gives true or false.

OperatorMeaningExample ($a = 5)Result
==Equal value$a == "5"true
===Equal value and same type$a === "5"false
!=Not equal$a != 3true
!==Not equal or different type$a !== 5false
>Greater than$a > 2true
<Less than$a < 2false
>=Greater or equal$a >= 5true
<=Less or equal$a <= 4false

Prefer === and !==. They check the type too, so they avoid surprises when a form sends the number "5" as text.

Logical Operators

  • && (and): true when both sides are true
  • || (or): true when at least one side is true
  • ! (not): turns true into false and false into true

if, elseif and else

Example

php
<?php
$marks = 72;

if ($marks >= 80) {
    echo "Grade A";
} elseif ($marks >= 60) {
    echo "Grade B";
} elseif ($marks >= 40) {
    echo "Grade C";
} else {
    echo "Fail";
}
Output
Grade B

PHP checks the conditions from top to bottom and runs only the first block whose condition is true.

Combining Conditions

Example

php
<?php
$age = 20;
$hasCnic = true;

if ($age >= 18 && $hasCnic) {
    echo "You can register for the course online.";
} else {
    echo "Please visit the institute with a guardian.";
}
Output
You can register for the course online.

The Ternary Operator

A short form of if/else for simple choices:

Example

php
<?php
$stock = 0;
echo $stock > 0 ? "In stock" : "Out of stock";
Output
Out of stock

The null coalescing operator ?? gives a default when a value is missing or null:

Example

php
<?php
$username = null;
echo "Hello, " . ($username ?? "Guest");
Output
Hello, Guest

switch

switch compares one value against many cases:

Example

php
<?php
$day = "Fri";

switch ($day) {
    case "Sat":
    case "Sun":
        echo "Weekend classes at 10 am";
        break;
    case "Fri":
        echo "Short day: classes end at 12";
        break;
    default:
        echo "Regular classes at 4 pm";
}
Output
Short day: classes end at 12

Do not forget break. Without it PHP continues into the next case.

match (PHP 8)

match is a cleaner, safer version of switch. It returns a value, uses strict comparison (===), and needs no break.

Example

php
<?php
$code = 404;

$message = match ($code) {
    200 => "OK",
    301, 302 => "Moved",
    404 => "Page not found",
    500 => "Server error",
    default => "Unknown status",
};

echo $message;
Output
Page not found

Exercise

Exercise

What is the result of 10 === "10" in PHP?

Learn PHP with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp