Lab4 PHP
Lab4 PHP
Preprocessor
Eng. Nada Bahaa Ibrahim
What is PHP?
• The switch statement is used to select one of many blocks of code to be executed.
<?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
• The loops are used to repeat code a certain number of times.
• In PHP, we have the following loop types:
• The while loop executes a block of code if the specified condition is true.
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
PHP do…..while Loop
• The do...while loop - Loops through a block of code once, and then
repeats the loop if the specified condition is true.
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
PHP for Loop
• The for loop is used when you know in advance how many times the
script should run.
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
PHP foreach Loop
• The foreach loop works only on arrays and is used to loop through each
key/value pair in an array.
<?php
$colors = array("red", "green", "blue", "yellow");
• The foreach loop works only on arrays and is used to loop through each
key/value pair in an array.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
PHP Functions
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
• Associative arrays are arrays that use named keys that you assign to
them.
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
• EX1:
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
• EX2:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>
Reference
• https://www.php.net/
• https://www.w3schools.com/php/default.asp