PHP Conditional Statements
PHP - The if Statement
<?PHP
echo date_default_timezone_get(). "<br>";
date_default_timezone_set("America/Chicago");
echo "Current date and time: " . date("Y-m-d H:i:s") . "<br>";
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
PHP - The if...else Statement
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The if...elseif...else Statement
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The switch Statement
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!";
}
?>
PHP Loops
PHP while Loops
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
PHP do...while Loop
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
PHP for Loops
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
PHP foreach Loop
<?php
$colors = ["red", "green", "blue", "yellow"];
foreach ($colors as $value) {
echo "$value <br>";
}
?>
Reference