All lessons

Making Decisions

7 min · PHP

Run different code depending on whether something is true.

PHP · Making Decisions0/5 cleared

Enemy 1 of 5

if / else and comparison operators

This code stores 5 in $temperature, then uses if and else to print Warm when it is above 20, or Cold if not. Press Run to see which one prints.

Why this works

Real programs need to behave differently depending on the situation, and if is the tool that makes that possible. An if statement evaluates a condition (an expression that's either true or false) and only runs the code in its { } block when that condition is true. Pair it with an else block to provide a fallback for every other case.

Conditions are built with comparison operators: > (greater than), < (less than), >= and <= (greater/less than or equal to), and == (equal to). Notice that's a double equals sign: a single = is assignment (storing a value), while == is comparison (asking a question). Mixing the two up is one of the most common bugs in almost every C-family language, PHP included, so it's worth burning into memory early: one = sets a value, two == asks if two things are equal.

PHP also has a stricter === operator, which checks that both the value AND the type match (so "5" == 5 is true, but "5" === 5 is false because one's a string and the other's an integer). Beginners can stick with == for now, but it's good to know === exists once type-related bugs start showing up.

You
Memory-Leak Rat
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.