Control structures

Simple if

<?php
$a = 4;
$b = 5;

if ($a < $b) {
  print("$a is less than $b");
}
?>

Result: 4 is less than 5

if / else

<?php
$a = 5;
$b = 4;

if ($a > $b) {
  print("$a is greater than $b");
}
else {
  print("$a is less than $b");
}
?>

Result: 5 is greater than 4

if / elseif / else

<?php
$a = 4;
$b = 4;

if ($a > $b) {
  print("$a is greater than $b");
}
elseif ($a == $b) {
  print("$a is equal to $b");
}
else {
  print("$a is less than $b");
}
?>

Result: 4 is equal to 4

Alternative syntax

<?php
$a = 4;
$b = 5;

if ($a < $b) :
  print("$a is less than $b"); 
endif;
?>

Result: 4 is less than 5

while

<?php
$i = 0;

while ($i < 10) {
  print($i++ . ' '); 
}
?>

Result: 0 1 2 3 4 5 6 7 8 9

for

<?php
$data = array(
  'red',
  'green',
  'blue'
);

for ($i = 0; $i < count($data); $i++) {
  print($data[$i] . ' '); 
}
?>

Result: red green blue

foreach

<?php
$data = array(
  'red' => '#F00',
  'green' => '#0F0',
  'blue' => '#00F'
);

foreach ($data as $item) {
  print($item . ' '); 
}
?>

Result: #F00 #0F0 #00F

<?php
foreach ($data as $key => $value) {
  print("$key : $value ");
}
?>

Result: red : #F00 green : #0F0 blue : #00F

switch

<?php
$day = date('l', time());

switch ($day) {
  case 'Sunday':
  case 'Saturday':
    print("It’s the weekend: $day.");
    break;

  default:
    print("It’s a weekday: $day.");
    break; 
}
?>

Result: It’s a weekday: Friday.

user-defined function

<?php
$day = date('l', time());

/**
 *  Wrapper for print()---appends a newline to the string.
 *  @param  string $s : optional
 *  @return string : just a newline if $s is blank
 */
function println($s = '')
{
  print($s . "\n");
}

switch ($day) {
  case 'Sunday':
  case 'Saturday':
    println("It’s the weekend: $day.");
    break;

  default:
    println("It’s a weekday: $day.");
    break;
}
?>

Result: It’s a weekday: Friday.