Chapter 4 PHP Lab

You might also like

You are on page 1of 37

Chapter 4:

BASICS OF PHP LAB EXERCISE

1
Phpsyntax.php
<?php
Echo” well come to IP php lab class”;
?>

2
Variable and its scope
varGlobalscope.php
<?php
$x = 5; varlocalscope.php
$y = 10; <?php
function myTest() { function myTest() {
global $x, $y; $x = 5; // local scope
$y = $x + $y; echo "<p>Variable x inside function is:
} $x</p>";
myTest(); }
echo $y; // outputs 15 myTest();
?> // using x outside the function will generate an
error
Staticscope,php echo "<p>Variable x outside function is:
<?php $x</p>";
function myTest() { ?>
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
Unit ?>PHP
Unit –– 7:
7: PHP 33 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Accessing global scope variable inside the function

Varglbinsidefunc.php Globalsindex.php
<?php <?php
$x = 15;
$x = 5;
$y = 10;
$y = 10;
function myTest() { function myTest() {
$GLOBALS['t'] = $GLOBALS['x'] +
global $x, $y;
$GLOBALS['y'];
$y = $x + $y; }
}
myTest(); myTest();
echo "the value is $t"; // outputs
echo $y; // outputs 15 25
?> ?>
Unit
Unit –– 7:
7: PHP
PHP 44 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
PHP - Constants
 define(name, value,)
Using const keyword
Defineconst.php Constconst.php
<?php
<?php
define("Department", "Welcome to
const Departemnt="Welcome to
Computer science department");
CS!";
echo Department; echo Departemnt;
?> ?>

5
Constants are global
Constglobal.php
<?php
define("Department", "Welcome to CS");
function myTest() {
echo Department;
}
myTest();
?>

6
Php operators
Arthimeticop.php echo "<br>";
<?php echo($x * $y);
$x = 10; echo "<br>";
$y = 4; echo($x / $y);
echo($x + $y); echo "<br>";
echo "<br>"; echo($x % $y);
echo($x - $y); ?>

7
Superglobal variables:-
Assignop.php $x = 5;
<?php $x *= 25;
$x = 10; echo $x;
echo $x; echo "<br>";
echo "<br>"; $x = 50;
$x = 20; $x /= 10;
$x += 30; echo $x;
echo $x; echo "<br>";
echo "<br>"; $x = 100;
$x = 50; $x %= 15;
$x -= 20; echo $x;
echo $x; ?>
echo "<br>";
8
increamentdecrement.php
<?php
$x = 10; echo $x;
echo $x++; echo "<hr>";
echo "<br>"; $x = 10;
echo --$x;
echo $x; echo "<br>";
echo "<hr>"; echo $x;
$x = 10; echo "<hr>";
echo $x++; $x = 10;
echo "<br>"; echo $x--;
echo "<br>";
echo $x;
?>

Unit
Unit –– 7:
7: PHP
PHP 99 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Logicalop.php
<?php
$year = 2021;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0)))
{
echo "$year is a leap year.";
} else{
echo "$year is not a leap year.";
}
?>
10
String.php
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
echo "<br>";
$x .= $y;
echo $x; // Outputs: Hello World!
?>

Unit
Unit –– 7:
7: PHP
PHP 11
11 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
PHP Conditional Statements
If.php
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>

12
 Ifelse.php

<?php  
$num=12;  
Ternaryop.php
if($num%2==0){  
<?php
echo "$num is even number";  
$age = 15;
}else{  
echo ($age < 18) ? 'Child' :
echo "$num is odd number";  
'Adult';
}  
?>
?>

13
Ifelseif.php
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>

14
Switch.php break;
<?php case "Fri":
$today = date("D"); echo "Today is Friday. Party
switch($today){ tonight.";
case "Mon": break;
echo "Today is Monday. Clean your case "Sat":
house."; echo "Today is Saturday. Its movie
break; time.";
case "Tue": break;
echo "Today is Tuesday. Buy some case "Sun":
food."; echo "Today is Sunday. Do some
break; rest.";
case "Wed": break;
echo "Today is Wednesday. Visit a default:
doctor."; echo "No information available for
break; that day.";
case "Thu": break;
echo "Today is Thursday. Repair }
your car."; ?>

15
Loops
 While.php
<?php Dowhile.php
$i = 1; <?php
while($i <= 3){ $i = 1;
$i++; do{
$i++;
echo "The number is " .
$i . "<br>"; echo "The number is " . $i .
"<br>";
}
}
?> while($i <= 3);
?>

16
Forloop.php
<?php
for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>";
}
?>

17
The PHP foreach Loop
foreachloop.php
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>

Exercise what is break , continue. Implement with example;

18
foreach$array key.php
 <?php
$myprofile = array(
"name" => “Ayisheshim Almaw",
"email" => “ayisheshim@mail.com",
"age" => 45
);
// Loop through superhero array
foreach($myprofile as $key => $value){
echo $key . " : " . $value . "<br>";
}
?>

19
PHP Indexed Arrays
 Example 1.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Example 2 Countelemnt.php
<?php <?php
$colors[0] = "Red"; $cars = array("Volvo", "BMW",
$colors[1] = "Green"; "Toyota");
$colors[2] = "Blue"; echo count($cars);
print_r($colors); ?>
?>
20
PHP Associative Arrays
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?> //loop with associative array
Or <?php
$age =
<?php array("Peter"=>"35",
$ages["Peter"] = "22"; "Ben"=>"37",
$ages["Clark"] = "32"; "Joe"=>"43");
$ages["John"] = "28"; foreach($age as $x =>
$x_value) {
echo "Key=" . $x . ",
// Printing array structure Value=" . $x_value;
print_r($ages); echo "<br>";
?> } 21
Adding items to an
array using the array
keyword Walking through an associative
array using foreach...as
<?php
<?php
$p1 = array("Copier", "Inkjet",
$paper = array('copier' =>
"Laser", "Photo");
"Copier & Multipurpose",
echo "p1 element: " . $p1[2] . 'inkjet' => "Inkjet Printer",
"<br>"; 'laser' => "Laser Printer",
$p2 = array('copier' => "Copier & 'photo' => "Photographic
Multipurpose", Paper");
'inkjet' => "Inkjet Printer", foreach ($paper as $item
'laser' => "Laser Printer", => $description)
'photo' => "Photographic Paper"); echo "$item:
$description<br>";
echo "p2 element: " . $p2['inkjet'] .
?>
"<br>"; ?> 22
Multidimensional Arrays
<?php
<?php // Define nested array
$cars = array $contacts = array(
( array(
"name" => "Peter Parker",
array("Volvo",22,18),
"email" => "peterparker@mail.com",
array("BMW",15,13), ),
array("Saab",5,2), array(
array("Land Rover",17,15) "name" => "Clark Kent",
); "email" => "clarkkent@mail.com",
echo $cars[0][0].": In stock: ".$cars[0] ),
[1].", sold: ".$cars[0][2].".<br>"; array(
echo $cars[1][0].": In stock: ".$cars[1] "name" => "Harry Potter",
[1].", sold: ".$cars[1][2].".<br>"; "email" => "harrypotter@mail.com",
)
echo $cars[2][0].": In stock: ".$cars[2]
);
[1].", sold: ".$cars[2][2].".<br>"; // Access nested value
echo $cars[3][0].": In stock: ".$cars[3] echo "Peter Parker's Email-id is: " .
[1].", sold: ".$cars[3][2].".<br>"; $contacts[0]["email"];
?> ?> 23
PHP Array Functions (implement with exercise)

 count($array) / sizeof($array)
 array_shift($array)
 array_pop($array)
 array_unshift($array,”New Item”)
 array_push($array,”New Item”)
 sort($array [, $sort_flags])
• SORT_REGULAR compare items normally (don’t change type)
• SORT_NUMERIC compare items numerically
• SORT_STRING compare items as string
• SORT_LOCALE_STRING compare items as string, based on the
current locale
 rsort($array [, $sort_flags])

Unit
Unit –– 7:
7: PHP
PHP 24
24 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
Implementing php function

 Functionbasic.php
<?php
function myfunction(){
echo"helow world";
}
myfunction();
?>

Unit
Unit –– 7:
7: PHP
PHP 25
25 Darshan
Darshan Institute
Institute of
of Engineering
Engineering &
& Technology
Technology
PHP Function Arguments
Funcargument.php
<?php Example
// Defining function <?php
function familyName($fname, $year)
function getSum($num1, $num2){
{
$sum = $num1 + $num2;
echo "$fname kebede. Born in
echo "Sum of the two numbers
$year <br>";
$num1 and $num2 is : $sum"; }
} familyName("Hege", "1975");
// Calling function familyName("Stale", "1978");
getSum(10, 20); familyName("Kai Jim", "1983");
?> ?>

26
PHP Function: Default Argument Value
Funcdefualtarg.php
Example 2
<?php
<?php
function sayHello($name="CS"){ function setHeight($minheight =
echo "ur Department is 50) {
$name<br/>"; echo "The height is :
} $minheight <br>";
sayHello("IT"); }
sayHello();//passing no value setHeight(350);
setHeight(); // will use the
sayHello("SW");
default value of 50
?> setHeight(135);
setHeight(80);
?>

27
Returning Values from a Function
 .

example1 example2
<?php <?php
// Defining function function cube($n){
function getSum($num1, return $n*$n*$n;
$num2){ }
$total = $num1 + $num2; echo "Cube of 3 is: ".cube(3);
return $total; ?>
}
// Printing returned value
echo getSum(5, 10); // Outputs:
15
?> 28
PHP Returning Array with Functions
<?php
// Defining function
function divideNumbers($dividend, $divisor){
$quotient = $dividend / $divisor;
$array = array($dividend, $divisor, $quotient);
return $array;
}
// Assign variables as if they were an array
list($dividend, $divisor, $quotient) = divideNumbers(10, 2);
echo $dividend . "<br>"; // Outputs: 10
echo $divisor . "<br>"; // Outputs: 2
echo $quotient . "<br>"; // Outputs: 5
?> 29
Passing Arguments to a Function by Reference

<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
$number *= $number;
return $number;
}
$mynum = 5;
echo $mynum . "<br>"; // Outputs: 5
selfMultiply($mynum);
echo $mynum . "<br>"; // Outputs: 25
?>

30
Including a PHP File into Another PHP File
<html> </head>
<head> <div id="section">
<?php <h2>London</h2>
include("header11.php"); <p>London is the capital city of England. It
require("menu.html"); is the most populous city in the United
require("rightmenu.php"); Kingdom,
require("leftmenu.php"); with a metropolitan area of over 13 million
inhabitants.</p>
?>
<p>Standing on the River Thames, London
<style>
has been a major settlement for two
#section { millennia,
width:350px; its history going back to its founding by the
float:left; Romans, who named it Londinium.</p>
padding:10px; </div>
} </body>
</style> </html>
<?php
require("footer.php");
?> 31
Exercise: what is require_one()& include_once()
PHP Form Handling
method GET vs POST

usingpostmethod.html
<html> <head> <title>Registration Form</title>
</head> <body> <h2>Registration Form</h2>
<form action="registration_form.php" method="POST">
First name: <input type="text" name="firstname"> <br>
Last name: <input type="text" name="lastname"> <input
type="submit" value="Submit"> </form> </body> </html>

Welcome.php
<html>
<body>
Welcome <?php echo $_POST["firstname"]; ?><br>
Your last name is: <?php echo $_POST["lastname"]; ?>
</body>
</html> 32
PHP Form Handling
method GET vs POST

usinggetmethod.html
<html> <head> <title>Registration Form</title>
</head> <body> <h2>Registration Form</h2>
<form action="registration_form.php" method=“GET">
First name: <input type="text" name="firstname"> <br>
Last name: <input type="text" name="lastname"> <input
type="submit" value="Submit"> </form> </body> </html>

Welcome.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html> 33
PHP Form processing (registration.html)

<html> <head></head> <tr> <td>gender</td>


<body> <td><input type="radio"
name="gender" value="male"> male
<form method ="POST" <input type="radio" name="gender"
action='formphp.php'> value="female"> female</td> </tr>
<table border="1px solid"> <tr> <td>Department</td> <td><select
<tr> <td>First name</td> name="dept">
<Option value="CS">CS</Option>
<td><input type="text" <Option value="IT">IT</Option>
name="fname"></td> </tr> <Option value="SW">SW</Option>
<tr> <td>Password</td> </select>
<td><input type="password" </td>
name="password"></td></tr> </tr> <td><input type="submit"
name="submit" value="submit"></td>
<tr><td>ID number</td> </tr>
<td><input type="number" </form></body></html>
name="number"></td>
</tr> 34
PHP Form processing (registration.phpl)
<?php
if(isset($_POST['submit'])) {
$fname=$_POST['fname'];
$password=$_POST['password'];
$number=$_POST['number'];
$gender=$_POST['gender'];
$dept=$_POST['dept'];
} ?>

35
PHP  Form Validation on (registration.phpl)
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = "";
$name = $email = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST[“fname"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST[“fname"]);
 }
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
 }
  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
 }
} 36
?>
PHP - Display The Error Messages

<form method="post" action="<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span> <br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span> <br><br>

Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

37

You might also like