php2
php2
Faisal Salaheldeen
STEM Obour
PHP if Statements
• Conditional statements are used to perform different actions
based on different conditions.
Syntax
• if (condition) {
code to be executed if condition is true;
}
• Example
• <?php
$x= 5;
if ($x > “3") {
echo "Have a good day!";
}
?>
PHP - The if...else Statement
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
• <?php
$x= 5;
if ($x > “3") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The if...elseif...else Statement
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 = 30;
• <?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 Arrays
An array stores multiple values in one single variable:
• <?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2]
. ".";
?>
• Example
• <?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
• Example2
• <?php
$x = 0;
• Syntax
• do {
code to be executed;
} while (condition is true);
• Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
for Loop
The for loop - Loops through a block of code a specified number
of times.
Syntax
• for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
foreach Loop
The foreach loop - Loops through a block of code for each
element in an array.
Syntax
• foreach ($array as $value) {
code to be executed;
}
Example
• <?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>