Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Chapter 5 PHP-Lecture 1

Chapter 5 of Web Programming (CoSc2042) focuses on PHP, a server-side scripting language used for creating dynamic and interactive web pages. It contrasts client-side and server-side scripting, detailing the advantages and functionalities of PHP, including its ability to interact with databases and generate dynamic content. The chapter also covers PHP syntax, variable handling, and the use of include and require functions for modular coding.

Uploaded by

Ayano Boresa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter 5 PHP-Lecture 1

Chapter 5 of Web Programming (CoSc2042) focuses on PHP, a server-side scripting language used for creating dynamic and interactive web pages. It contrasts client-side and server-side scripting, detailing the advantages and functionalities of PHP, including its ability to interact with databases and generate dynamic content. The chapter also covers PHP syntax, variable handling, and the use of include and require functions for modular coding.

Uploaded by

Ayano Boresa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Web Programming (CoSc2042 )

Chapter 5 PHP

1
Compiled By: Kassawmar M. (MSc)
Introduction
• HTML- focuses on marking up information(define the
content of web pages)
• CSS- focuses on formatting and presenting information
(specify the layout of web pages)
• JavaScript to program the behavior of web pages
( to add dynamic features on the client side)
• PHP is a server scripting language, and a powerful tool f
or making dynamic and interactive Web pages.
( used to add dynamic features on the server side…
including database interaction)
Static VS Dynamic Web Sites
• Static Websites-Written in HTML
• Dynamic Websites – do more interactive things.
– Markup language like HTML
– Scripting (both client and server side) language 2
– Style sheet (for presentation) like CSS
– PHP with DB interaction
Common Web Application Architecture

Requests
Browser Server

Responses

Requests
Responses
Responses
Script
Database Engine
Requests

3
Client-side Technologies
CLIENT
SIDE Server

Browser

HTML
JavaScript
CSS

Script
Database Engine

4
Server-Side

Browser Server

Apache

SERVER SIDE

Database Script
Engine PHP
MySQL

5
Client-side vs. Server-side scripting
• Client-side scripting
– The execution of scripts on the client's web browser rather than on
the web server.
– Validates user input
– Accesses the browser
– Enhances Web pages with HTML, CSS, JS etc.
– Manipulates browser documents
• Client-side validation
– Reduces number of requests that need to be passed to server
– It helps improve the user experience by providing immediate
feedback to users
– Enhanced Responsiveness: This means that users can receive
immediate feedback and continue interacting with the form or
application without waiting for server validation
• Client-side scripting limitations
– Browser dependency
– Viewable to users through View Source command (it can be
accessed and manipulated by the user)
– Security Risks: Client-side scripts are executed on the clients6
machine, which introduces security risks
– Limited Data Validation.
Cont…
• Server-side scripts
– The execution of scripts on the server to generate dynamic
web content before sending it to the client's web browser
– Provides programmers greater flexibility
– Generates custom responses for clients
– Contains greater programmatic capabilities than client-side
equivalents
– The common server-side technologies are:
• Hypertext Preprocessor (PHP)
• Java Servlets
• Java Server Page (JSP)
• Common Gateway Interface (CGI)
• Mod Perl 7

• Active Server Pages (ASP)


Client side vs Server side scripting
Client-side Server-side
Scripts are stored on the client Scripts are stored on the
(engine is in browser) server (engine is on server)
Scripts can be modified by the Scripts cannot be modified by the
end user end user
Browser-dependent Browser-independent
Source code can be viewed Source code can’t be viewed
Can’t communicate with a database Can communicate with a database

No network overhead Dependent on network bandwidth

Processing is done by the Processing is done by the


browser - fast server- slower

8
Common Features of server-side frameworks

• All server-side frameworks share a common


set of features
– Read data submitted by the user
– Generate HTML dynamically based on user input
– Determine information about the client browser
– Access database systems
– Utilize the HTTP protocol

9
Decision Points
• When evaluating which server-side technology to
use, you need to consider a number of critical
factors:-
– Ease of development
• How easily can you build new applications
– Performance
• How fast can the technology respond to queries
– Scalability
• Can the technology scale to thousands, even millions of
users?
– Security
10
• Are there any inherent security vulnerabilities?
Server-Side Scripting (cont’d)

Advantages of Server-Side Scripting


• Dynamic content
• Computational capability
• Database and file system access
• Network access (from the server only)
• Built-in libraries and functions
• Security improvements
• Code Reusability
• Cross-Platform Compatibility: Server-side scripting
languages and technologies are typically
platform-independent.
11

11 Internet Programming
What is PHP?
• PHP is a scripting language, created in 1994 by
Rasmus Lerdorf from the Apache Group, that is
designed for producing dynamic Web content.
• PHP stands for Hypertext Preprocessor
• It is a widely-used, open source scripting language
• It scripts are executed on the server
• It is a scripting language designed specifically for
use on the web.
• It has features to aid you in programming the tasks
needed to develop dynamic web applications.
• Its similarity to C’s syntax and open-source nature
make PHP relatively easy to learn. 12
Cont…
• PHP is another huge language
 It is a fully functional language
 It has an incredible amount of built-in features
• Form processing
• Output / generate various types of data
• Database access
 Allows for various DBs and DB formats
• Object-oriented features
 Somewhat of a loose hybrid of C++ and Java

13
Cont..
• PHP is an embedded scripting language, meaning that it
can exist within HTML code.
• It is a server-side technology, everything happens on the
server as opposed to the Web browser’s computer, the client.
• It is Platform Independent: meaning it can be used on
Linux, Windows, Mac, etc., making PHP very portable.
• It is compatible with almost all servers used today (Apache,
IIS, etc.)
• It is easy to learn and runs efficiently on the server side
• PHP supports many databases (MySQL, Informix, Oracle,
Sybase, Solid, PostgreSQL, Generic ODBC, etc.)

14
What is a PHP File?

• PHP files can contain text, HTML, JavaScript


code, and PHP code
• PHP code are executed on the server, and the
result is returned to the browser as plain HTML.
• PHP files have a file extension of ".php"

15
What Can PHP Do?
• PHP can generate dynamic page content (PHP allows web
developers to create web pages that can display different
content based on various conditions, inputs, or data
retrieved from databases or other sources.)
• PHP can create, open, read, write, and close files on the
server.
• It can collect form data
• It can send and receive cookies
• It can add, delete, modify data in your database
• It can restrict users to access some pages on your
website.
• It can encrypt data 16
Why PHP?
• Powerful and flexible,
• PHP is easy to learn and runs efficiently on the
server side
• PHP runs on different platforms (Windows, Linux,
Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
• PHP has support for a wide range of databases
(MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc)
• PHP is an open source software and free to download
and use.
• Cheap and easy to set up
17
Basic PHP Syntax
<html><head></head>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
• <?php tag informs the server that PHP code is to follow.
• The ?> tag closes out the PHP mode with the server resuming
its scanning in HTML mode once more.
• Each code line in PHP must end with a semicolon.
• The semicolon is a separator which is used to
distinguish one set of instructions from another.
• With PHP, there are two basic statements to output text in 18
the browser: echo and print.
Example Cont…
HTML 5 Document
<!DOCTYPE html>
<html> Root HTML Tag
<head>
<title>Simple PHP Example</title>
</head> Document Head
<body>
<?php echo "<p><h1>Output</h1>";
D echo "<h2>Output</h2>";
O echo "<h3>Output</h3></p>";
C PHP Code
?>
<?php
B echo "<b>More PHP Output</b>";
O echo "<br/>";
D
echo "New line in source but not rendered";
Y
echo "<br/>";
echo "New line rendered but not in source";
?>
</body> 19
</html>
Comments in PHP
• In PHP, three different kinds
(a)// ... ; for single line
(b)# ... ; for single line
(c)/* ... */ ; for multiple-line
<html>
<body>
<?php
//This is a comment
# this is also a comment
/*
This is a comment
block
*/
?></body> 20

</html>
Example Cont…
<?php
// This is a single-line comment using double slashes
echo "Hello, World!"; // Output: Hello, World!
/*
This is a multi-line comment.
It spans multiple lines and can contain multiple statements.
*/
echo "This is a multi-line comment."; /* Output: This is a multi-line
comment. */
# This is a single-line comment using a hash symbol
echo "This is another comment."; # Output: This is another
comment.
?>
21
Script execution
• There are two methods for executing PHP
scripts:
 Via the Web server, and
 The command-line interface (CLI).
• The first method will be used almost exclusively
in this course, so you may ignore the CLI for
now.

22
How to run php file on XAMPP server?

XAMPP start Apache and


installation MYSQL from Install Notepad++
XAMPP

The file in XAMP installation directory or write php program or code


web root directory. Default XAMP on text editor.
installation directory for windows is
C/xampp
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: 23

http://localhost/folder_name/filename.php
The use of include() and require() function
• In PHP, the include() and require() functions are used to
include and execute external PHP files within another PHP
file.
• These functions help in modularizing code and reusing
common functionality across multiple files.
• The main difference between include() and require() lies in
how they handle file inclusion errors.
include() Function:
• The include() function includes and executes the specified file.
• If the file is not found or encounters an error during inclusion, a
warning is issued, but the script continues to execute.
• It has the following syntax: include('filename');
require() Function:
• The require() function includes and executes the specified file.
• If the file is not found or encounters an error during inclusion, a fatal 24
error is issued, and the script execution is halted.
• It has the following syntax: require('filename');
Cont…
Example
setdate.php:
<?php $today=getdate(time());?>
footer.php:
<SMALL>Today is <?php
print $today[weekday];?></SMALL>
Index.php:
<?php
include ("setdate.php");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<?php include ("footer.php"); ?>
25

Note: you can use require() instead of include() in the above example
PHP Variables
• 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;
• All variables in PHP start with a $ sign symbol.
<?php
$txt="Hello World!";
$x=16;
?>
• In PHP, a variable does not need to be declared before adding a value
to it.
• PHP is a Loosely Typed Language (variables are not bound to a
specific data type, can change during run-time. 26
Rules for PHP variable

• A variable name must begin with a letter or the


underscore or dollar sign character.

• A variable name can only contain alpha-numeric


characters and underscores (A-z, 0-9, and _ )
• A variable name should not contain spaces

• Variable names are case sensitive ($y and $Y are


two different variables) 27
Example
<!DOCTYPE html>
<html>
<body>
<?php
$txt = “Php variable example!";
$x = 30;
$y = 20.5;
echo $txt; echo "<br>";
echo $x; echo "<br>";
echo $y;
?>
</body>
</html> 28
Environment/predefined Variables
• PHP provides a set of environment or predefined
variables called "superglobals variables" that are
available in all scopes throughout a script.
• All of these environment variables are stored by PHP as
arrays.
• Some you can address directly by using the name of the
index position as a variable name. Other can only be
accessed through their arrays.
• These variables contain information about the
environment, server, and user.
• Some commonly used superglobals variables in PHP
are:
29
Cont…
Some of the environment variables include:
• $_SERVER
 Contains information about the server and
the HTTP connection. Analogous to the old
$HTTP_SERVER_VARS array (which is
still available, but deprecated).
• $_COOKIE
 Contains any cookie data sent back to the
server from the client. Indexed by cookie
name. Analogous to the old
$HTTP_COOKIE_VARS array (which is still
available, but deprecated).
30
Cont…
• $_GET
 Contains any information sent to the server as a search
string as part of the URL. Analogous to the old
$HTTP_GET_VARS array (which is still available, but
deprecated).
• $_POST
 Contains any information sent to the server as a POST style
posting from a client form. Analogous to the old
$HTTP_POST_VARS array (which is still available,
but deprecated).
• $_FILE
 Contains information about any uploaded files. Analogous
to the old $HTTP_POST_FILES array (which is still
available, but deprecated).
• $_ENV
 Contains information about environmental variables on the
server. Analogous to the old $HTTP_ENV_VARS array 31

(which is still available, but deprecated).


PHP Variable Scopes

• PHP has three different variable scopes:


 Local
 Global
 Static

32
Cont…
Local scope
• A variable declared within a PHP function is
local and can only be accessed within that
function:
<?php
$x=5; // global scope
function myTest()
{
$x=6; // local scope
echo $x; // local Scope
}
?>
• Local variables are deleted as soon as the
function is completed 33
Global scope Cont…
• A variable declared outside a function has a GLOBAL
SCOPE and can be accessed outside a function:
• The global keyword is used to access a global variable from
within a function(use the global keyword before the variables
(inside the function))
<?php
$x=5; // global scope
$y=10; // global scope
Function myTest(){
global $x,$y;
$y=$x+$y;
}
myTest(); 34
echo $y; // outputs 15
?>
Cont…
• PHP also stores all global variables in an array called
$GLOBALS[index].
• The index holds the name of the variable.
• This array is also accessible from within functions and
can be used to update global variables directly.
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest(); 35
echo $y; // outputs 15
?>
Static scope Cont…
• Sometimes you want local variable to not be deleted for future use.
• To do this, use the static keyword when you first declare the var:
• A variable with static scope retains its value between multiple
function calls.
• Static variables are defined within a function but persist even
after the function finishes executing.
• Static variables are initialized only once and retain their value
across subsequent function calls.
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;}
myTest(); // 0
myTest(); // 1
myTest(); // 2 36
?>
PHP Data Types
• Variables can store data of different types, and
different data types can do different things.
• PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL

37
Fundamental variable types
• Numeric
 integer. values outside this range are converted to floating-point.
 float. Floating-point numbers.

• Boolean: true or false; PHP internally resolves these to 1 (one) and 0 (zero)
respectively.
• string: String of characters.
• array: An array stores multiple values in one single variable.(an array of
values, possibly other arrays )

• 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.

• Null : data type with only one possible value: null. Marks variables as being
empty. Works with the isset() operator; will return ‘false’ for null.
Example:
$var=NULL; 38
Cont…
• PHP has a useful function named var_dump() that
prints the current type and value for one or more
variables.
• The PHP var_dump() function returns the data type
and value:
• Arrays and objects are printed recursively with their
values indented to show structure.
Output of the code
$a = 35;
int(35)
$b = "Programming is fun!"; string(19) "Programming is fun!"
array(4) {
$c = array(1, 1, 2, 3);
[0]=> int(1)
var_dump($a,$b,$c); [1]=>int(1) 39
[2]=>int(2)
[3]=>int(3
PHP Strings
• A string is a sequence of characters, like "Hello
world!".
• A string can be any text inside quotes. You can use single
or double
'I am a string in single quotes'
"I am a string in double quotes"
• The PHP parser determines strings by finding matching
quote pairs. So, all strings must start and finish with the
same type of quote - single or double.
• Only one type of quote mark is important when
defining any string, single (') or double (").
$string_1 = "This is a string in double quotes";
$string_0 = ‘’ // a string with zero characters
40
String Concatenation Operator
• To concatenate two string variables together,
use the dot (.) operator:
E.g
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 ." " .$txt2;
?>
Output
41
Hello World! What a nice day!
The strlen()function
• The strlen() function is used to find the length
of a string.
E.G
<?php
echo strlen("Hello world!");
?>
Output
12
• The length of a string is often used in loops
or other functions, when it is important to
know when the string ends. 42
The strpos()function
• The strpos() function is used to search for a string
or character within a string. (first position in the
string is 0)
• If a match is found in the string, this function will
return the position of the first match. If no match
is found, it will return FALSE.
E.g
<?php
echo strpos("Hello world!","world"); // output=6
?> 43
The str_word_count() function
• The PHP str_word_count() function counts the number
of words in a string:
E.g
<?php
echo str_word_count("Hello world!"); //output =2
?>
Reverse a String
• The PHP strrev() function reverses a string:
E.g <?php
echo strrev("Hello world!"); //output=!dlrow olleH
?>
44
The str_replace() function
• The PHP str_replace() function replaces some
characters with some other characters in a string.
<?php
echo str_replace("world", "PHP", "Hello world!");
?> Output: Hello PHP!
• In this case, the function is called with the following
arguments:
o "world": This is the substring to be replaced.
o "PHP": This is the replacement substring.
o "Hello world!": This is the original string.
o The str_replace() function searches for all occurrences of
the substring "world" within the string "Hello world!" and 45
replaces them with the substring "PHP"
PHP Math Functions
abs() base_convert()  mt_getrandmax() sin()
acos() bindec()
ceil()  getrandmax()  sinh()
acosh()  mt_rand()
asin() cos()
 hexdec()  sqrt()
asinh() cosh()  mt_srand()
atan() decbin()  hypot()  srand()
dechex()  octdec()
atan2()
atanh() decoct()  is_finite()  tan()
 pi()pow()
exp() expm1()
 is_infinite()  tanh()
 rad2deg()
 is_nan()  max()
 rand()
 lcg_value()  min()
 round()
 log()log10()  Fmod()
 deg2rad()
 log1p() 46

 floor()
PHP Constants
• A constant is an identifier (name) for a simple value. The
value cannot be changed during the script.
• A valid constant name starts with a letter or underscore
(no $ sign before the constant name).
• Note: Unlike variables, constants are automatically
global across the entire script.
• Syntax
define(name, value, case-insensitive)
// 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
• E. g
<?php
// case-sensitive constant name
define("GREETING", "Welcome to Hawassa University!");47
echo GREETING;
?>
PHP Operators
• Operators are used to perform operations
on variables and values.
• PHP divides the operators in the
following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators 48
PHP Arithmetic Operators Cont…
Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y / Result of raising $x to the $y'th 49


pow($x, $y) power
PHP Assignment Operators Cont…

Assignment Same as... Description

x=y $x = $y The left operand gets set to the value


of the expression on the right

x += y $x = $x + $y Addition

x -= y $x = $x - $y Subtraction

x *= y $x = $x * $y Multiplication

x /= y $x = $x / $y Division

x %= y $x = $x % $y Modulus 50
PHP Comparison Operators
Cont…
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the
same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of
the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than $x >= $y Returns true if $x is greater than or equal to $y


or equal to
51
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
PHP Increment / Decrement Operators
Cont…
Operator Name Description

++$x Pre-increment Increments $x by one,


then returns $x
$x++ Post-increment Returns $x, then
increments $x by one

--$x Pre-decrement Decrements $x by one, then


returns $x

$x-- Post-decrement Returns $x, then


decrements $x by one

52
PHP Logical Operators Cont…
Operator Name Example Result

and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but


not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true 53


Cont…
PHP String Operators

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of


$txt1 and $txt2

.= Concatenati on $txt1 .= $txt2 Appends $txt2 to


assignment $txt1

Example
$txt1 = "Hello";
$txt2 = " world!"; 54
$txt1 .= $txt2;
echo $txt1; // Output: Hello world!
PHP Array Operators Cont…
Operator Name Example Result
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have
the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the
same key/value pairs in the same
order and of the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal


to $y
!== Non-identity $x !== $y Returns true if $x is not
identical to $y 55
PHP Conditional Statements
• Conditional statements are used to perform
different actions based on different conditions
• In PHP we have the following conditional
statements:
• if statement - executes some code only if a
specified condition is true
• if...else statement - executes some code if a
condition is true and another code if the condition
is false
• if...else if....else statement - specifies a new
condition to test, if the first condition is false
• switch statement - selects one of many blocks of 56
code to be executed
PHP - The if Statement Cont…
• The if statement is used to execute some
code only if a specified condition is
true.
• Syntax
if (condition) {
code to be executed if condition is true;
}
• Example
<?php
$t = date("H"); //24 hours format of an hour
if ($t < “15") {
echo "Have a good day!";
} 57

?>
PHP - The if...else Statement
Cont…
• Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
• Example
<?php
$t = date("H");
if ($t < "12") {
echo "Have a good day!";
}
else {
echo "Have a good night!";
} 58
?>
PHP - The if...else if....else Statement Cont…
• 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;
}
Example
<?php
$d=date("D"); // A textual representation of a day (three letters)
if($d=="Fri")
echo "Have a nice weekend!";
Else if($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!"; 59

?>
Cont…
PHP switch statement
Example

<?php
$favcolor = "black";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
} 60
?>
PHP looping statements
PHP Looping - While Loops
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?> 61
Cont…

PHP Looping – do-while Loops


<?php
$i= 1;
do {
echo "The i value is: " . $i. "<br>";
$i++;
} while ($i<= 5);
?>
62
PHP Looping - For Loops
Cont…
E.g
<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x
<br>";
}
?>
</body> 63
</html>
Cont…
• The foreach loop works only on arrays, and is used to
loop through each key/value pair in an array
• 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, until it reaches the last array element.
E.g.
<?php
$x=array("one","two","three");
foreach($x as $value)
{
echo $value . "<br />";
} 64
?>
PHP Functions
• Functions are at the heart of a well-organized script and will
make your code easy to read and reuse.
• In PHP, functions come in two flavors – those built-in to the
language, and those that you define yourself.
• Function Definition defined using the function keyword,
followed by the function name, parentheses for parameters
(if any), and the function body enclosed in curly braces.
• User defined functions may be declared as follows:
<?php
function function_name($arg_1, $arg_2, ..., $arg_n)
{
// function body
[return $retval;]
} 65

?>
• PHP does not support function overloading.
Example Cont…
<?php
Function writeName(){
echo "samy abebe";
}
echo "My name is "; writeName();
?>

Adding parameters
<?php
function writeName($fname)
{
echo $fname . "abebe<br/>";
}
echo "My name is ";
writeName("sam");
echo "My sister's name is "; 66

writeName("Helen");
?>
PHP Functions - Return values
Cont…
• The return statement is used to specify the
value that a function should return.
• It terminates the execution of the function and
sends the specified value back to the caller.
<?php
function add($x,$y)
{
$total=$x+$y;
Return $total;
}
echo "1 + 16 = " . add(1,16); 67

?>
PHP Arrays
• An array is a data structure that stores one or
more similar type of values in a single value.
• In PHP, there are three types of arrays:
 Numeric/Indexed array - An array with a
numeric index. Values are stored and
accessed in linear fashion.
 Associative array - An array with strings as
index. This stores element values in association
with key values rather than in a strict linear
index order.
 Multidimensional arrays- Arrays containing
one or more arrays 68
Numeric Array Cont…
• A 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.
E.g
<html><body>
<?php
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br/>";
}
?> 69

</body>
</html>
Associative array
Cont…
• Associative array will have their index as string so that
you can establish a strong association between key and
values.
• To store the salaries of employees in an array, a
numerically indexed array would not be the best choice.
• Instead, we could use the employees names as the keys
in our associative array, and the value would be their
respective salary.
<?php
$salary= array("abel"=>3200, "Sam"=>3000, "bet"=>3400);
echo "Salary of Abel is ". $salary['abel'] . "<br />";
echo "Salary of betty is ". $salary['bet'] . "<br
/>"; echo "Salary of samy is ". $salary['sam'] .
"<br />";
?> 70
Cont…
Multidimensional array

• In a multidimensional array, each element in the


main array can also be an array. And each element
in the sub-array can be an array, and so on.
• Values in the multi-dimensional array are accessed
using multiple index.

$families = array (
"Griffin"=>array ("Peter","Lois","Megan"),
"Quagmire"=>array ("Glenn"),
"Brown"=>array("Cleveland","Loretta","Junior")
);
echo "Is " . $families['Griffin'][2] . " a part of the Griffin 71
family?";
//output: Is Megan a part of the Griffin family?
<html><body> Cont…
<?php
$marks = array( /*Accessing multi-dimensional
"abel" => array( array values */
"physics" => 35, echo "Marks for abel in physics : " ;
"maths" => 30, echo $marks['abel']['physics'] . "<br
/>";
"chemistry" => 39),
echo "Marks for sam in maths : ";
"sam" => array(
echo $marks['sam']['maths'] . "<br
"physics" => 30, />";
"maths" => 32, echo "Marks for sam in chemistry : "
"chemistry" => 29), ;
"beti" => array( echo $marks['sam']['chemistry'] .
"<br />";
"physics" => 31, ?> </body></html>
"maths" => 22,
"chemistry" => 39)
72
);
Mixing array types
Cont…
⚫ We can even mix the two if we'd like
 PHP arrays are a cross between numbered arrays and
associative arrays.
In the example below, three literal arrays are declared as follows:
1. A numerically indexed array with indices running from 0 to 4.
2. An associative array with string indices.
3. A numerically indexed array, with indices running from 5 to 7.
<?php
$array1 = array(2, 3, 5, 7, 11);
$array2 = array("one" => 1,
"two" => 2,
"three" => 3);
$array3 = array(5 => "five", "six", "seven");
print($array1[3]); 73
print($array2["one"]);
print($array3[5]); ?>
Get The Length of an Array Cont…
<?php
$cars=array("Volvo","BMW","Toyota"); echo
count($cars); // print 3
?>
Loop Through an Indexed Array
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x]; echo
"<br>";
/*print Volvo
BMW
Toyota */ 74
}
?>
Cont…
Loop Through an Associative Array

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"4 3");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x. ", Value=" . $x_value;
echo "<br>";
}
?>

75
PHP Functions For Sorting Arrays
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order,
according to the value
• ksort() - sort associative arrays in ascending order,
according to the key
• arsort() - sort associative arrays in descending order,
according to the value
• krsort() - sort associative arrays in descending order,
according to the key.
<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
// Sorting and printing array in Ascending Order
76
sort($colors);
print_r($colors);
?>
Cont…
Sorting Indexed Arrays
<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
// Sorting and printing arrayin Descending Order
rsort($colors);
print_r($colors);
?>
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);
?>
77
Sorting Associative Arrays Cont…
<?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); ?>

<?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);
?>

78
79

You might also like