PHP & MySQL - Conditional - Looping
PHP & MySQL - Conditional - Looping
6
PHP Loop Types
• Loops in PHP are used to execute the same block of code a
specified number of times.
• Result
The while loop statement
• The while statement will execute a block of code if and as long as a
test expression is true.
• Syntax
• Example
• Result
The do...while loop statement
• The do...while statement will execute a block of code at least once -
it then will repeat the loop as long as a condition is true.
• Syntax
• Example
• Result
The foreach loop statement
• The foreach statement is used to loop through arrays.
• For each pass the value of the current array element is assigned to
$value and the array pointer is moved by one and in the next pass
next element will be processed.
• Syntax
• Example
• Result
PHP
Arrays
• An array is a special variable, which can store multiple values
in one single variable.
• There are three kind of arrays:
• Numeric array - An array with a numeric index
• Associative array - An array where each ID key is associated with
a value
• Multidimensional array - An array containing one or more arrays
Numeric Arrays
• A numeric array stores each array element with a numeric
index.
• There are two methods to create a numeric array.
• the index are automatically assigned (the index starts at
0).
$cars=array("Saab","Volvo","BMW","Toyota");
• assign the index manually.
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
• Example: access the variable values by referring to the array
name and index.
• Output:
Saab and Volvo are Swedish
cars.
Associative Arrays
• An associative array, each ID key is associated with a value.
• Example: Lets try displaying a single value from the array above.
• NRP 1 – 5: if-else
• NRP 6-10: switch-case
• NRP 11-15: do-while
• NRP 16-20: for-loop
• NRP 21-30:while
Abi
<?php
$mhs = array(
array(’nama’=>”Labba”,’nrp’=>61,’ipk’=>3.15,’rambut’=>array(”hitam”,”lurus”),’bb’=>50,’tb’=>160,’st
atus’=>”aktif”),
array(’nama’=>”Awwabi”,’nrp’=>62,’ipk’=>3.35,’rambut’=>array(”coklat”,”berombak”),’bb’=>70,’tb’=>17
0,’status’=>”cuti”),
array(’nama’=>”Abi”,’nrp’=>63,’ipk’=>3.5,’rambut’=>array(”merah”,”lurus”),’bb’=>90,’tb’=>180,’statu
s’=>”aktif”),
);
for($i=0;$i<$mhs.lenght();$i++) if($mhs[$i]
[’ipk’]>3 && $mhs[$i][’ipk’]<3.25)
if($mhs[$i][’rambut’][0]==”hitam” &&
$mhs[$i][’rambut’][1]==”lurus”)
if($mhs[$i][’bb’]==50 &&
$mhs[$i][’tb’]==160)
if($mhs[$i][’status’]!
=”cuti”)
echo ”nama : ”.
$mhs[$i]
[’nama’].”
<br/>nrp :
”.$mhs[$i][’nrp’].”<hr/>”;
?>
RANGGA
<?php
$mhs = array(
array(’n
ama’=>”L
abba”,’n
rp’=>61,
’ipk’=>3
.15,’ram
but’=>ar
ray(”hit
am”,”lur
us”),’bb
’=>50,’t
b’=>160,
’st
atus’=>”aktif”)
;
$i = 0;
do{
if($mhs[$i][’ipk’]>3 && $mhs[$i][’ipk’]<3.25){ if($mhs[$i][’rambut’]
[0]==”hitam” && $mhs[$i][’rambut’][1]==”lurus”){
?> if($mhs[$i][’bb’]==50 && $mhs[$i][’tb’]==160){
if(!$mhs[$i][“isCuti”]){
echo $mhs[$i][“nrp”].” “.$mhs[$i]