revision:
Syntax:
if (condition) {
code to be executed if condition is true;
}
example:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
Syntax:
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
example:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a nice day!";
} else {
echo "Have a good night!";
}
?>
Syntax:
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
example:
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good and splendid day!";
} else {
echo "Have a good night!";
}
?>
Use the switch statement to select one of many blocks of code to be executed.
Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
example:
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
Syntax:
while (condition is true) {
code to be executed;
}
example:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Syntax:
do {
code to be executed;
} while (condition is true);
example:
<?php
$x = 1;
do {
echo "The number is: $x
";
$x++;
} while ($x <= 5);
?>
Syntax:
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
- init counter : initialize the loop counter value;
- test counter : evaluated for each loop iteration; if it evaluates to TRUE, the loop continues; if it evaluates to FALSE, the loop ends;
- increment counter : increases the loop counter value
example:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Syntax:
foreach ($array as $value) {
code to be executed;
}
example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $val) {
echo "$x = $val<br>";
}
?>
The break statement can be used to jump out of a loop.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
Break and continue can also be used in while loops.
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}
?>