You are on page 1of 100

CHAPTER

ONE
Server Side Scripting Basics
Introduction to server-side scripting
2

Contents To be Covered
!  Server-side scripting languages

!  Use Basic Syntax

!  Send Data to the Web Browser

!  Write Comments

!  Data Types and Utilize Variables

!  Manipulate Strings, Date Time


ManipulationConstants,Operators,Numbers

!  Control Statements ,Arrays ,Functions,


Working with Objects
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
3

Web Application
! Architecture : client-server
architecture
! Client : web browser
! primary language for web browsers is
HTML (how the web page is presented )
! And including more plug-ins like
RealPlayer, Flash, and Shockwave.
! Work with XML
! Support Java script

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
4

Web Application
! Server :
! almost all of the work of Web
applications takes place on the
server.
!  specific application, called a Web
server, will be responsible for
communicating with the browser.(apache or
Internet information server)
!  A relational database server stores
whatever information the application
requires.
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
5

Web Application
! Finally, you need a language to
broker requests between the Web
server and the database server;
! it will also be used to perform
programmatic tasks on the information
that comes to and from the Web
server.
! The Web server, programming language,
and database server you use must work
well with your operating system.
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
6

Web Application
! Operating System
! Manage computer resources
! Server OS or OS
! Different OS (windows ,mac ,Linux etc)

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


7

Web Application: Architecture


Middleware
Web (PHP,ASP,JSP) Data Base
Server (MySql ,Oracle)
(Apache, IIS)

Web Browser
(internet explorer ,Netscape,Mozila etc)

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


8

What is PHP ?
!  PHP stands for PHP: Hypertext Preprocessor

!  PHP is a server side scripting language.

!  PHP is an interpreted language,i.e.there is no need


for compilation.

!  PHP is an object-oriented language.

!  PHP is an open-source scripting language.

!  PHP is simple and easy to learn language.

!  PHP supports many databases (MySQL, Informix, Oracle,


Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
9

PHP Features

! Performance:
!  Script written in PHP executes much faster
then those scripts written in other
languages such as JSP & ASP.

! Open Source Software:


!  PHP source code is free available on the
web, you can developed all the version of
PHP according to your requirement without
paying any cost.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


10

PHP Features
! Platform Independent:
!  PHP are available for WINDOWS, MAC, LINUX
& UNIX operating system. A PHP application
developed in one OS can be easily executed
in other OS also.

! Compatibility:
!  PHP is compatible with almost all local
servers used today like Apache, IIS etc.

! Embedded:
!  PHP code can be easily embedded within HTML
tags and script.
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
How to run php file on XAMPP 11
server?
XAMPP start Apache
installation and MYSQL from Install Notepad++
XAMPP

the file in XAMP installation directory or web write php program or


root directory. Default XAMP installation
directory for windows is C/xampp code on text editor.

In the xampp directory there is htdocs


directory open the directory and create
folder and give any name.

save all php file to the folder you are


creating with .php extension name.

In your browser address bar, type the address:


http:/localhost/folder_name/filename.php
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
12

Server Side Scripting Language ?


!  A typical web server today contains four
elements in addition to the physical
hardware.

!  LAMP (Linux, Apache, MySQL, and PHP)


WAMP (Windows, Apache, MySQL, & PHP)

!  XAMPP (Apache, MariaDB , Perl and PHP)


!  PHP
!  ASP
!  Perl

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


13

Basic Syntax

Tag style Starting tag Ending tag
Standard <?php ?>
Short hand <? ?>
ASP <% %>
Script <script language=“php”> </script>

php can be saved .php or embedded into html.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


14

Errors
!  Notice

!  Warning

!  Error

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


15

Basic Syntax
!  PHP code is executed on the server, and the
plain HTML result is sent to the browser
!  create a file and write HTML tags + PHP code
and save this file with .php extension.
!  Each code line in PHP must end with a
semicolon (;)
!  <?php //your code here ?> or
<!DOCTYPE>
<html>
<body>
<?php echo "<h2>Hello World!</h2>”; ?>
</body>
</html>
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
16

Send output to the browser?


!  echo;

!  print();

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


17

PHP echo /Print


! Printing string
<?php echo "Hello world"; ?>
Output: Hello world
! Printing multi line string File:
<?php echo "Hello by PHP echo
this is multi line text "; ?>
Output: Hello by PHP echo this is multi line
text

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


18

PHP echo

! Printing variable value:


<?php
$msg="Hello world";
echo "Message is: $msg";
?>
Output: Message is: Hello world

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


19

PHP Comments
!  Purpose :
!  To provide information /readable code/
!  To hide codes
There are two ways:
! single line comments
!  // (C++ style single line comment)
!  # (Unix Shell style single line
comment)
! Multiple line comments
!  enclose all lines within /* */

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


20

Example: PHP comments


<?php
//single line comment
echo “ hello world!”;
/* Multiple line
Comment */ Output: hello
world!
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


21

PHP Variables and Data Types


!  A variable in PHP is a name of memory
location that holds data.

!  A variable is a temporary storage that


is used to store data temporarily.

!  In PHP, a variable is declared using $


sign followed by variable name.

!  Syntax of declaring a variable in PHP


is given below:
$variablename=value;

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


22

!  In PHP, a variable does not need to be


declared before adding a value to it.

!  the variable is declared automatically when


you use it.

!  PHP automatically converts the variable to the


correct data type, depending on its value.

!  The PHP var_dump() function returns the data


type and value:Example
<?php
$x = 5985;
var_dump($x);
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


23

Naming Rules for Variables


!  A variable name must start with a letter or an
underscore "_"

!  A variable name can only contain alpha-numeric


characters and underscores (a-z, A-Z, and _ )

!  A variable name should not contain spaces.

!  If a variable name is more than one word, it


should be separated with an underscore
($my_string)or with capitalization ($myString).


Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
24

Example :
<?php

$str="hello string"; OutPut:


String is : hello string
$x=100; Integer is:100
Float is: 22.5
$y=22.5;

echo ”String is: $str<br/>";
echo ”Integer is: $x<br/>";
echo ”Float is: $y<br/>";

?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


25

PHP Boolean
! A Boolean represents two possible
states: TRUE or FALSE.
$x = true;
$y = false;
! Booleans are often used in
conditional testing.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


26

PHP Array

!  An array stores multiple values in one
single variable.
!  In the following example $cars is an
array.
!  The position of array elements starts
from 0 not 1
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
echo $cars[0];
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


27

PHP NULL Value


!  Null is a special data type which can have
only one value: NULL.
!  A variable of data type NULL is a variable
that has no value assigned to it.
Tip: If a variable is created without a
value, it is automatically assigned a value of
NULL.
!  Variables can also be emptied by setting the
value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
28

<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


29

PHP Object

!  An object is a data type which stores
data and information on how to process
that data.

!  In PHP, an object must be explicitly


declared.

!  First we must declare a class of object.

!  For this, we use the class keyword.

!  A class is a structure that can contain


properties and methods
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
30
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$h= new Car();

// show object properties
echo $h->model;
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


31

Manipulate Strings

! A PHP string is a sequence of


characters i.e. used to store and
manipulate text.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


32

Single Quoted PHP String


! enclosing text in a single quote
<?php
$str='Hello world within single quote';
echo $str;
?>

Output: Hello world within single quote

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


Multiple line text, special 33
characters and escape sequences in a
single quoted String

<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>

!  Output:
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


Note: In single quoted PHP strings, most 34
escape sequences and variables will not be
interpreted. But, we can use single quote
through \' and backslash through \\ inside
single quoted PHP strings
<?php

$num1=10;

$str1='trying variable $num1';

$str2='trying backslash n and backslash t inside single quoted string \n \t';

$str3='Using single quote \'my quote\' and \\backslash';

echo "$str1 <br/> $str2 <br/> $str3";

?>

Output:

trying variable $num1


trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


35

Double Quoted PHP String


!  enclosing text within double quote also.
!  But escape sequences and variables will
be interpreted using double quote PHP
strings.
<?php

$str="Hello text within double quote
";
echo $str;
?>
!  Output: Hello text within double quote

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


36

Cont’d
!  You can't use double quote directly inside double
quoted string.
<?php
$str1="Using double "quote" directly inside double quoted
string";
echo $str1;
?>

!  Output: error

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


37

Cont’d
!  We can store multiple line text, special characters and escape
sequences in a double quoted PHP string.
<?php
$str1="Hello text
multiple line
text within double quoted string”;
$str2="Using double \"quote
\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>

!  Output: Hello text multiple line text within double quoted


string Using double "quote" with backslash inside double quoted
string Using escape sequences in double quoted string
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019

38

In double quoted strings,
variable will be interpreted
<?php
$num1=10;
echo "Number is: $num1";
?>
!  Output: Number is: 10

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


39

The Concatenation Operator



!  There is only one string operator in PHP.

!  The concatenation operator dot(.) is used


to put two string values together.

!  To concatenate two string variables


together, use the concatenation operator
dot(.): example:
<?php
$txt1=“I’m interested!";
$txt2=“with php!";
echo $txt1 . " " . $txt2;
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


40

PHP String Functions


1) strtolower()
!  returns string in lowercase letter.
!  Syntax
strtolower ( string $string )

!  Example
<?php
$str=”Hello STUDENT";
$str=strtolower($str);
echo $str;
?>

!  Output: hello student

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


41

PHP String Functions


2) strtoupper()
!  returns string in uppercase letter.

!  Syntax
strtoupper ( string $string )

!  Example
<?php
$str="Hello STUDENT";
$str=strtoupper($str);
echo $str;
?>

!  Output: HELLO STUDENT


Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
42

PHP String Functions


3) ucfirst()
!  returns string converting first character into
uppercase.
!  It doesn't change the case of other characters

!  Syntax
ucfirst ( string $str )
Output : Hello STUDENT
!  Example
<?php
$str=“hello STUDENT";
$str=ucfirst($str);
echo $str; ?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019

43

PHP String Functions


4) lcfirst()
!  returns string converting first character into
lowercase.
!  It doesn't change the case of other

!  Syntax
lcfirst ( string $str )
Output: hello
!  Example Student
<?php
$str=“Hello Student";
$str=lcfirst ($str);
echo $str; ?>
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
44

PHP String Functions


5) ucwords()
!  returns string converting first character of
each word into uppercase.

!  Syntax
!  string ucwords ( string $str )

!  Example
Output: Hello
<?php Student
$str=”hello student";
$str=ucwords($str);
echo $str;
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
45

PHP String Functions


6) strrev()

!  returns reversed string.

!  Syntax
strrev ( string $string )

!  Example
Output: tneduts
<?php
olleh
$str=”hello student";
$str=strrev($str);
echo $str;
?>
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
46

PHP String Functions


7) strlen()
!  returns length of the string.

!  Syntax :
strlen( string $string )

!  Example :
<?php Output: 13
$str=”hello student";
$str=strlen($str);
echo $str;
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


47

PHP String Functions


8. strpos() :The PHP strpos() function searches
for a specific text within a string.
!  If a match is found, the function returns the
character position of the first match.
!  If no match is found, it will return NULL.

!  The example below searches for the text "world"


in the string "Hello world!":
<?php
echo strpos("Hello world!", "world");
// outputs 6
? > The output of the code above will be: 6.

Tip: The first character position in a string is


0 (not 1).

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
48

PHP String Functions



9.str_replace() :The PHP str_replace() function
replaces some characters with some other
characters in a string.

!  The example below replaces the text "world"


with ”dave":

Example
<?php
echo str_replace("world", ”Dave", "Hello
world!");
?>
// outputs Hello Dave!

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


49

PHP Math Functions


!  sin()
!  abs() !  base_convert() !  getrandmax() !  mt_getrandmax()
!  sinh()
!  acos() !  bindec() !  hexdec() !  mt_rand()
!  sqrt()
!  acosh() !  ceil() !  hypot() !  mt_srand()
!  srand()
!  asin() !  cos() !  is_finite() !  octdec()
!  tan()
!  asinh() !  cosh() !  is_infinite() !  pi()pow()
!  tanh()
!  atan() !  decbin() !  is_nan() !  rad2deg()
!  max()
!  atan2() !  dechex() !  lcg_value() !  rand()
!  min()
!  atanh() !  decoct() !  log()log10() !  round()
!  Fmod()
!  exp() !  expm1() !  log1p() !  deg2rad()
!  floor()

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
50

Constants
!  PHP constants are name or identifier that can't be
changed during the execution of the script.

!  PHP constants can be defined by 2 ways:


!  Using define() function
!  Using const keyword

!  PHP constants follow the same PHP variable rules.

!  No $ sign before the constant name.

!  Conventionally, PHP constants should be defined in


uppercase letters.

!  Note: Unlike variables, constants are automatically


global across the entire script.
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
51

Syntax
define(name, value, case-insensitive)
Parameters:
!  Name: Specifies the name of the constant
!  Value: Specifies the value of the
constant
!  Case-insensitive: Specifies whether the
constant name should be case-
insensitive. Default is false

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


52

Example:
! The example below creates a constant
with a case-sensitive name:

<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


53

PHP constant: const keyword


! The const keyword defines constants


at compile time.
! It is a language construct not a
function.
! It is bit faster than define().
! It is always case sensitive.


Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
54

Example

<?php
const MESSAGE="Hello const by PHP";
echo MESSAGE;
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


55

Array

!  An array is a special type of variable that


can hold many values at once, all
accessible via a single variable name.

!  Arrays are very useful whenever you need to


work with large amounts of data — such as
records from a database — or group related
data together.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


56

Types of Arrays in PHP



! There are three types of arrays that
you can create. These are:
! Indexed array
! An array with a numeric key.
! Associative array
! An array where each key has
its own specific value.
! Multidimensional array
! An array containing one or
more arrays within itself.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


57

Indexed Arrays

! An indexed or numeric array stores
each array element with a numeric
index.
! Note: In an indexed or numeric
array, the indexes are automatically
assigned and start with 0, and the
values can be any data type.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


58

Indexed array
<?php

// Define an indexed array

$colors = array("Red”,"Green”,"Blue");
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


59

Associative Arrays

!  In an associative array, the keys assigned
to values can be arbitrary and user defined
strings.
<?php

// Define an associative array


$ages = array ("Peter"=>22,"Clark"=>32,"John"=>28);
$ages["Peter"] = "22";
$ages["Clark"] = "32";
$ages["John"] = "28";
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


60

Multidimensional Arrays

! is an array in which each element


can also be an array and each
element in the sub-array can be an
array or further contain array
within itself and so on.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


61

Example:
<?php

$marks = array( "mohammad" => array ( "physics" => 35,"maths" => 30, "chemistry" => 39 ),
"abebe" => array ("physics" => 30,"maths" => 32, "chemistry" => 29 ),

"zara" => array ( "physics" => 31, "maths" => 22, "chemistry" => 39 ) );

// Accessing multi-dimensional array values

echo "Marks for mohammad in physics : " ; echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for abebe in maths : ”;echo $marks['abebe']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;echo $marks['zara']['chemistry'] . "<br />";

?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019



62
Viewing Array Structure and
Values

<?php
// Define array
$cities = array(“Addis", “DB", “Nazret");
// Display the cities array
var_dump($cities);
?>

<?php
// Define array
$cities = array(“Addis", “DB", “Nazret");
// Display the cities array
print_r($cities);
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
63

PHP Functions For Sorting Arrays



! sort() and rsort() — For sorting
indexed arrays
! asort() and arsort() — For sorting
associative arrays by value
! ksort() and krsort() — For sorting
associative arrays by key

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


64

Sorting Indexed Arrays



<?php
// Define array
$colors = array("Red", "Green", "Blue”,"Yellow");
// Sorting and printing array in Ascending Order
sort($colors);
print_r($colors);
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


65

Sorting Indexed Arrays



<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
// Sorting and printing arrayin Descending Order
rsort($colors);
print_r($colors);
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


66

Sorting Associative Arrays



<?php
// Define array

$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);


// Sorting array by value and print in Ascending Order By Value
asort($age);
print_r($age);
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


67

Sorting Associative Arrays



<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14,"John"=>45, "Clark"=>35);
// Sorting array by value &print in Descending Order By Value
arsort($age);
print_r($age);
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


68

Sorting Associative Arrays



<?php

// Define array

$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);

// Sorting array by key and print in Ascending Order By Key

ksort($age);

print_r($age);

?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


69

Operators and expressions


! Operators :
! they are symbols use to manipulate
values.
! Operand :
! is a value operate by the operator/s.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


70

Operators
PHP Operators can be categorized in following
forms:
!  Arithmetic Operators

!  Comparison Operators

!  Bitwise Operators

!  Logical Operators

!  String Operators

!  Assignment Operators

!  Incrementing/Decrementing Operators

!  Array Operators

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


71

! We can also categorize operators on


behalf of operands.
! They can be categorized in 3 forms:
! Unary Operators: works on single
operands such as ++, -- etc.
! Binary Operators: works on two
operands such as binary +, -, *, /
etc.
! Ternary Operators: works on three
operands such as "?:".
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
72

Arithmetic Operators :Example


<?php
$x = 10; $y = 6;
echo($x+$y)."<br>"; //output 16
echo($x-$y)."<br>"; //output 4
echo($x*$y)."<br>"; //output 60
echo($x/$y)."<br>"; //output 1.67
echo($x%$y)."<br>"; //output 4
echo ++$x."<br>"; // output 11
echo --$y."<br>"; // output 5
echo $x++."<br>"; // output 11
echo $y--."<br>"; // output 5
?>
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
73

Control statements
!  Conditional statements
!  If
!  If..else
!  If..elseif..else
!  Switch

!  Loops
!  While
!  Do..while
!  For

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


74

Conditional Statements
!  Conditional statements are used to perform
different actions based on different conditions.

!  if statement - use this statement to execute some


code only if a specified condition is true

!  if...else statement - use this statement to execute


some code if a condition is true and another code
if the condition is false

!  if...elseif....else statement - use this statement


to select one of several blocks of code to be
executed

!  switch statement - use this statement to select one


of many blocks of code to be executed

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


75

The if Statement

!  Use the if statement to execute some code
only if a specified condition is true.

Syntax

!  if (condition) code to be executed if


condition is true;

!  The following example will output "Have a


nice weekend!" if the current day is Friday:

!  <?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


76

if...else :Syntax

!  The if...else Statement

!  Use the if....else statement to execute some


code if a condition is true and another code
if a condition is false.
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


77

Example :if ..else


!  The following example will output "Have a
nice weekend!" if the current day is Friday,
otherwise it will output "Have a nice day!":

!  <?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


78
The if...elseif....else
Statement

!  Use the if....elseif...else statement to
select one of several blocks of code to be
executed.

!  Syntax

if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is
false;

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


79

Example: if..elseif..else
!  The following example will output "Have a
nice weekend!" if the current day is Friday,
and "Have a nice Sunday!" if the current day
is Sunday. Otherwise it will output "Have a
nice day!":
!  <?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!";
?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


80

PHP Switch Statement



!  Use the switch statement to select one of many blocks
of code to be executed.

!  Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
……………….
break;
default:
code to be executed if n is different
from both label1 and label2;
}

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


81

Switch Statement con’t.


!  This is how it works: First we have a single
expression n (most often a variable), that is
evaluated once.
!  The value of the expression is then compared
with the values for each case in the
structure.
!  If there is a match, the block of code
associated with that case is executed.
!  Use break to prevent the code from running
into the next case automatically.
!  The default statement is used if no match is
found.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


82

Example: Switch Statement



<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>


Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
83

PHP Looping - While Loops


!  Loops execute a block of code a specified number of
times, or while a specified condition is true.

!  In PHP, we have the following looping statements:

!  while - loops through a block of code while a


specified condition is true

!  do...while - loops through a block of code once,


and then repeats the loop as long as a 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

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


84

The while Loop



!  The while loop executes a block of code while
a condition is true.
!  Syntax
while (condition)
{
code to be executed;
}
!  Example
!  The example below defines a loop that starts
with i=1. The loop will continue to run as
long as i is less than, or equal to 5. i will
increase by 1 each time the loop runs:

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


85

Example: while loop


!  <?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>
Output:
!  The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


86

The do...while Statement



!  The do...while statement will always execute the block of code
once, it will then check the condition, and repeat the loop
while the condition is true.

!  Syntax

do
{
code to be executed;
}
while (condition);

!  Example

!  The example below defines a loop that starts with i=1. It will
then increment i with 1, and write some output. Then the
condition is checked, and the loop will continue to run as
long as i is less than, or equal to 5:

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


87

Example: do…while
!  <?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br />";
}
while ($i<=5);
?>
Output:
!  The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


88

PHP Looping - For Loops


!  The for loop is used when you know in advance how
many times the script should run. Syntax :
for (init; condition; increment)
{
code to be executed;
}

!  Parameters:
!  init: Mostly used to set a counter (but can be any code to be executed
once at the beginning of the loop)
!  condition: Evaluated for each loop iteration.If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
!  increment: Mostly used to increment a counter (but can be any code to
be executed at the end of the loop)

!  Note: Each of the parameters above can be empty, or have


multiple expressions (separated by commas).

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


89

Example :for loop


!  The example below defines a loop that starts with
i=1. The loop will continue to run as long as i is
less than, or equal to 5. i will increase by 1 each
time the loop runs:
!  <?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br />";
}
?>

!  Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


90

The foreach Loop


!  The foreach loop is used to loop through arrays.

Syntax
foreach ($array as $value)
{
code to be executed;
}

!  For every loop iteration, the value of the current array element
is assigned to $value (and the array pointer is moved by one) -
so on the next loop iteration, you'll be looking at the next
array value.

Example

!  The following example demonstrates a loop that will print the


values of the given array:

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


91

Example: foreach
<?php

$data=array("abebe"=>2,"belen"=>1,”feven"=>5);
foreach($data as $name=>$id)
{
echo $data[$id];
}

?>

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


92

Functions
!  A function is a named block of code that is
designed to perform a specific task.

!  Once a function is defined, you can reuse


it without copying and pasting a code block
again and again.

!  A function may accept one or more


arguments, which are the values that you
pass to the function.

!  A function may return a value so that the


calling script can communicate with it.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


93

Create a PHP Function


!  A function will be executed by a call to the
function.

!  Syntax
function function_Name()
{
code to be executed;
}

!  PHP function guidelines:


!  Give the function a name that reflects what the
function does
!  The function name can start with a letter or
underscore (not a number)

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


94

Creating and calling functions



<?php
function function_name(parameter1,
parameter2,...){
//function body code
}
?>

function_name(parameter1, parameter2,...);

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


95

PHP Functions
!  The real power of PHP comes from its
functions.

!  In PHP, there are more than 700 built-in


functions.

!  when the page loads, you can put it into a


function.

!  A function will be executed by a call to


the function.

!  You may call a function from anywhere


within a page.
Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019
96

Example
A simple function that writes name when it is
called:
!  <?php
function writeName()
{
echo “mrx";
}

echo "My name is ";
writeName();
?>

!  Output:
My name is mrx

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


97

Function parameters

!  Information can be passed to functions
through arguments. An argument is just like a
variable.

!  Function may accept one or more parameters.


There are two ways to pass parameters to a
function: passing parameter by value and
passing parameter by reference.

!  Parameter is what's given in the function


declaration/definition.

!  Argument is what's passed when calling the


function.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


98


Passing parameters by
value

Passing parameters by
reference
<?php <?php

function increase($x){ function increase(&$x){

$x = $x + 1; $x = $x + 1;

echo 'inside function x = ' . $x .'<br />'; echo 'inside function x = ' . $x .'<br />';

} }

$x = 10; $x = 10;

increase($x); increase($x);

echo 'outside function x = ' . $x .'<br />'; echo 'outside function x = ' . $x .'<br />';

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


99

Benefits of using function



!  Functions are reusable – Because a function
is designed to perform a specific independent
task so that it can be reused in other web
applications.

!  Functions help avoid duplicate code – A


function helps avoid copying and pasting code
all over places by wrapping the logic and
assigning it a name.

!  Functions make your script modular – by using


functions, a big script is divided into many
functions that are easier to build, test and
maintain.

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019


10
0

Advanced IP Compiled By: Yonas H. (MSc.) 5 April 2019

You might also like