DB Lab 9
DB Lab 9
Learning objectives:
Learn to use basic PHP syntax.
Learn to use PHP conditional statements.
Learn to use PHP arrays.
Learn to use PHP loops.
<?php
Echo "Hello World!";
?>
Comments in PHP
Single-line and multi-line comments are same as in C++.
<?php
// single-line comment
echo "Hello World!";
/*
Multi-line comment
*/
?>
PHP Variables
A variable in PHP starts with $ sign and data types are determined at run time.
<?php
$a;
$a = "Hello World!";
echo $a;
$a = 5;
echo $a;
$b = 20;
echo $a + $b;
?>
Strings are concatenated using . operator.
<?php
$a = 5;
$b = 20;
$c = $a+$b;
echo "Sum of a and b is " . $c;
?>
The <br> tag is used to insert a single line break (new line).
<?php
$a = 5;
$b = 20;
$c = $a+$b;
echo "Sum of $a <br> and $b <br> is " . $c;
?>
Syntax is same as in C++ and for reference only we will use an example of if .. else block.
<?php
$a = 5;
$b = 20;
if ($a < $b)
{echo "a is smaller";}
else
{echo "b is smaller";}
?>
9.3 PHP Indexed Arrays
An array stores multiple values under a single variable name. In PHP array() function is used to create
an array.
<?php
$arr[0] = 1;
$arr[1] = 2;
$arr[2] = 3;
$arr[3] = 4;
$arr[4] = 5;
echo $arr[4];
?>
<?php
$arr = array (1, 2, 3, 4, 5);
echo $arr[0] . $arr[1] . $arr[2] . $arr[3] . $arr[4];
?>
<?php
$arr = array (6, 2, 5, 11, 0);
sort($arr);
echo $arr[0]."<br>".$arr[1]."<br>".$arr[2]."<br>".$arr[3]
."<br>".$arr[4];
?>
<?php
$fruits = array ('apple', 'orange', 'coconut', 'grapes');
rsort($fruits);
echo $fruits[0].", ".$fruits[1].", ".$fruits[2].",
".$fruits[3];
?>
<?php
$fruits = array ('apple', 'orange', 'coconut', 'grapes');
echo "The number of fruits are: " . count($fruits);
?>
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
<?php
$a = 1;
while($a <= 5)
{
echo "$a <br>";
$a++;
}
?>
<?php
for ($a = 5; $a >= 1; $a--)
{
echo "$a <br>";
}
?>
<?php
$student = array("Alex", "Noah", "Cole", "Smith");