View Category

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
php
if($name == "Bob") {
echo "Hello, Bob!";
}

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
php
if($age < 42) {
echo "You are young";
} else {
echo "You are old";
}
echo "You are " . (($age < 43) ? "young" : "old");

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

php
echo "You are " . (($age > 84) ? "really ancient" : (($age > 30) ? "middle-aged" : "young"));
$response = "You are ";
if ($age > 84) {
$response .= "really ancient";
} else if ($age > 30) {
$response .= "middle-aged";
} else {
$response .= "young";
}
echo $response;

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
php
function suffix($n) {
switch ($n) {
case ($n % 100 >= 4) && ($n % 100 <= 20):
return 'th';
case $n % 10 == 1:
return 'st';
case $n % 10 == 2:
return 'nd';
case $n % 10 == 3:
return 'rd';
default:
return 'th';
}
}
for ($n=1; $n<=40; $n++) {
echo $n . suffix($n) ."\n";
}

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
php
$x = 1;
while($x < 150) {
echo "$x,";
$x *= 2;
}
$x = 0;
$c = pow(2, $x);
while($c < 150) {
echo "$c,";
$c = pow(2, $x++);
}

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
php
do {
$rand = rand(1,6);
echo $rand;
if ($rand != 6) echo ", ";
} while ($rand != 6);

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
php
for($i = 0; $i < 5; $i++) {
echo "Hello";
}

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
php
for($i = 10; $i > 0; $i--) {
echo $i." .. ";
}
echo "Liftoff!";