Professional Documents
Culture Documents
Chapter 2-2 PHP Decision and Loops
Chapter 2-2 PHP Decision and Loops
CHAPTER 2:
PHP Decision & Loops (2 of 5)
Topics covered:-
if, else and else if statement
switch statement
Ternary operator
do, while and for statement
break and continue statement
Nested Loops
Decision Making
• You have learnt to make decision using if-else
statement, else if statement and switch statement
using C programming language in the course
AACS1074 and AACS1084 Programming Concept and
Design I (PCD I) and PCDII.
/*
* Demonstrating if-else statement
*/
$basic = 5000;
$manager = true;
$allowance = 0;
if($basic > 1000 && $manager == true)
$allowance += 300;
else
$allowance += 50;
/*
* Demonstrating if-else statement
*/
$basic = 5000;
$manager = true;
$allowance = 0;
if($basic > 1000)
if($manager == true)
$allowance += 300;
else
$allowance += 50;
$leapYear = false;
if((($year % 4 == 0) && ($year % 100 != 0)) || ($year % 400 == 0)){
$leapYear = true;
}
echo "<p>Did you know that $year is " . ($leapYear ? " " : " not ") . "a leap year?</p>";
?> Refer to code example: displayGreeting
• Example:
date_default_timezone_set(“Asia/Kuala_Lumpur”);
getdate() Returns an array that contains date and time information for a
Unix timestamp
[seconds] - seconds ,[minutes] - minutes , [hours] - hours
[mday] - day of the month , [wday] - day of the week , [year] - year
[yday] - day of the year , [weekday] - name of the weekday ,
Looping
• Allows to run the same block of code again and again until
a certain condition is met.
• The condition is an expression. If the expression evaluated
to true, the loop continues. Otherwise, the loop exit.
• Three (3) main types of loops:-
• while
• do … while
• for
while() loop
$countDown = 10;
do … while() loop
$total = 0;
$radius = 1;
$count = 1;
$area = 0;
define("PI", 3.14159);
$area = PI * pow($radius,2);
$total += $area;
echo "[$count] Calculated area of a circle with radius $radius<br>";
echo "Total area of circles : " . $total . "<br>";
$radius += 1;
$count += 1;
}while($radius <= 5); Refer to code example: looping
AMIT 2043 Web Systems and Technologies
PHP Decision & Loops (Part 2 of 5) Slide 16
for() loop
$total = 0;
$radius = 1;
$count = 1;
$area = 0;
define("PI", 3.14159);
$total = 0;
$radius = 1;
$count = 1;
$area = 0;
define("PI", 3.14159);
$total = 0;
$radius = 1;
$area = 0;
define("PI", 3.14159);
$asteriskArray;
for($i = 1; $i <= 6; $i++){
echo "<br>";
for($j = 1; $j <= 10; $j++){
$asteriskArray[$i][$j] = "*";
echo $asteriskArray[$i][$j];
}
}