0% found this document useful (0 votes)
31 views101 pages

Advanced IP-Chapter-1 - Lect-1, 2

The document provides an introduction to server-side programming using PHP. It defines PHP and scripting languages, compares client-side and server-side scripting, and outlines some key advantages and capabilities of using PHP for web development.

Uploaded by

Abrham Tegegne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views101 pages

Advanced IP-Chapter-1 - Lect-1, 2

The document provides an introduction to server-side programming using PHP. It defines PHP and scripting languages, compares client-side and server-side scripting, and outlines some key advantages and capabilities of using PHP for web development.

Uploaded by

Abrham Tegegne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 101

Chapter 1: Introduction to Server-Side

Programming – PHP
What is a Scripting Language?
• A script is a set of programming instructions that is
interpreted at runtime.
• A scripting language is a language that interprets
scripts at runtime. Scripts are usually embedded into
other software environments.
• The purpose of the scripts is usually to enhance the
performance or perform routine tasks for an
application.
1
Programming Language Vs Scripting Language
Programming language Scripting language

Has all the features needed to develop complete Mostly used for routine tasks
applications.
The code has to be compiled before it can be The code is usually executed without compiling
executed
Does not need to be embedded into other Is usually embedded into other software
languages environments.

• What is PHP?
• PHP is the most popular server-side scripting language for creating
dynamic web pages. PHP stands for Hypertext Preprocessor.
• PHP is a very popular and widely-used open source server-side
scripting language to write dynamically generated web pages.
• PHP was originally created by Rasmus Lerdorf in 1994.
• It was initially known as Personal Home Page.

2
Cont...
• PHP scripts are executed on the server and
the result is sent to the web browser as
plain HTML.
• PHP can be integrated with the number of
popular databases, including MySQL,
PostgreSQL, Oracle, Microsoft SQL Server,
Sybase, and so on

3
Static VS Dynamic Web Sites
Static Dynamic

Simple to code (HTML only) Complex coding (HTML +


scripting + style sheet)

No database connection Usually connects to either flat


files or a database

Quick to develop Takes longer to develop

No user interaction Emphasizes on user


interaction (e.g. fill up a form,
login) 4
Client-Side Scripting VS Server-Side Scripting -
Overview

Client side Server side


Webserver

HTML* PHP engine

HTML PHP

5
Client-Side Scripting VS Server-Side
Scripting - Overview
Common Web Application Architecture:

Requests
Browser Server

Responses

Requests
Responses
Responses
Script
Database Engine
Requests

6
Client-side Technologies
CLIENT
Server
SIDE

Browser

HTML
JavaScript
CSS

Script
Database Engine

7
Server-Side
Browser Server

Apache

SERVER SIDE

Database Script PHP


MySQL Engine

8
Client-Side Scripting VS Server-Side Scripting - Comparison

Client-side Server-side
Scripts are stored on the Scripts are stored on the
client (engine is in browser) server (engine is on server)
Scripts can be modified by the Scripts cannot be modified by
end user the end user
Browser-dependent Browser-independent
Source code can be viewed Source code can’t be viewed
Can’t communicate with a Can communicate with a
database database
No network overhead Dependent on network
bandwidth
Processing is done by the Processing is done by the
browser – fast server - slower 9
Advantages and Capabilities of PHP
Main Arguments for the Use of PHP
– PHP Compared to ASP/Active server page
– PHP and Java
– PHP or Perl/ practical extraction and report
language

10
Main Arguments for the Use of PHP
Main Reasons to Use PHP
Powerful and flexible

Easy to learn

C-like and therefore a generalizable skill

Extremely portable

Cheap

Easy to set up

Works with lots of databases

Availability of source code (you can even contribute!)


11
Introduction to Server-Side Programming – PHP

• PHP is one of the most prevalent Web programming languages


for creating dynamic Web content.
• Its similarity to C’s syntax and open-source nature make PHP
relatively easy to learn.
• PHP is a scripting language, created in 1994 by Rasmus Lerdorf
from the Apache Group, that is designed for producing
dynamic Web content.
• PHP originally stood for “Personal Home Page,” but as its
functionality expanded, it became “PHP: Hypertext Processor”
because it takes PHP code as input and produces HTML as
output.
• PHP is especially suited for web development and can be
embedded into HTML.
12
PHP…
• Its primary use is for server-side scripting
 Ex: To process HTML forms
 PHP scripts are often embedded within html
documents
 The server processes the html document,
executing the PHP segments and substituting the
output within the html document
• PHP scripts are executed on the server.
• PHP is used for form handling, file processing, and
database access.
13
PHP…
• PHP supports many databases (MySQL, Informix,
Oracle, Sybase, Solid, PostgreSQL, Generic ODBC,
etc.).
• PHP is an open source software and free to download
and use.
• PHP files are returned to the browser as plain HTML.
• PHP files have a file extension of ".php", ".php3", or
".phtml“.
• PHP files can contain text, HTML tags and scripts.
• PHP is similar to JavaScript, only server-side

14
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 (not just
text)
• Database access
– Allows for various DBs and DB formats
• Object-oriented features
– Somewhat of a loose hybrid of C++ and Java

15
PHP is…
• interpreted rather than compiled like Java or C.
• an embedded scripting language, meaning that it can
exist within HTML code.
• a server-side technology; everything happens on the
server as opposed to the Web browser’s computer, the
client.
• cross-platform, meaning it can be used on Linux,
Windows, Macintosh, etc., making PHP very portable.
• compatible with almost all servers used today (Apache,
IIS, etc.)
• easy to learn and runs efficiently on the server side

16
PHP does not…
– handle client-side tasks such as creating a new
browser window, adding mouseovers,
determining the screen size of the user’s machine,
etc. Such tasks are handled by JavaScript or Ajax
(Asynchronous JavaScript and XML).
– do anything within the Web browser until a
request from the client has been made (e.g.,
submitting a form, clicking a link, etc.).

17
Why use PHP?
• PHP has been described as being “better, faster, and
easier to learn than the alternatives.” The alternatives
being…
• HTML – static, no database/file interaction,
cannot handle email, etc.
• Microsoft ASP (Active Server Pages), or ASP.NET –
need to learn VBScript, C#, or another language
and is limited to servers running Microsoft
Windows Server.
• Macromedia ColdFusion – expensive to purchase.
18
• JSP (JavaServer Pages) – Java-based, so there is a
higher learning curve plus you deal with the
overhead of a compiled language. Personal
experience also suggests that JavaServer sites are
slower than other sites.
• Additionally, PHP is free, works on multiple
platforms, and is open source (i.e., user-driven
development, not part of a corporation).
• These attributes combined with a large
development community and the wealth of available
PHP libraries make PHP an attractive choice for Web
developers.

19
How do Web Servers work?
 Client specifies document at a specific web
address that is desired (specified by a URL)
– Ex: http://www.bdu.edu.et
 If the document is html or text, the server simply
forwards it back to the client
– It is then rendered in the client's browser
 However, if it has embedded PHP, the server first
executes the PHP, replacing the PHP code with its
output in the document
 The modified document is then sent to the client

20
• The Web content delivery process has the same
beginning and end:
– A user requests a URL from the Web server, and
– HTML markup is sent to the user’s browser.
– With the static HTML delivery process, the Web
server sends the exact content of the requested page
to the client without any additional processing.
– With dynamic Web content creation, PHP acts as a
filter by processing PHP code – possibly embedded
within HTML markup – to produce HTML markup
that is ultimately sent to the user’s browser.

21
• Note that the client never sees the PHP code
– This is important – typically client should not see
logic / code that server executes to process
requests
– The server may be accessing files whose names
should not be seen, or preprocessing data that it
does not want the client to see
– The only reason the client even knows PHP is
involved is due to the file extension  .php
– But even this is not required if the server is
configured correctly.
22
Embedding PHP code
• To give you an idea of what embedding PHP would entail, consider the
following three "hello world" examples.
• all of which will give the exact same output:
Example 1: HTML alone
Hello, World!
Example 2: PHP code alone
<?php
print "Hello, World!";
?>
Example 3: PHP embedded within HTML
<?php
print "Hello,";
?> World!

23
Embedding PHP code…..
• Web servers supporting PHP will, by default, scan a file
in HTML mode.
• HTML code will be passed over to the browser as usual,
up until the server happens upon a PHP line of code.
• In examples 2 and 3 above, the <?php tag informs the
server that PHP code is to follow.
• The server then switches over to PHP mode in
anticipation of a PHP command.
• The ?> tag closes out the PHP mode with the server
resuming its scanning in HTML mode once more.

24
Embedding PHP code…..
• Embedding code in this manner is, conceptually, a
more fluid approach to designing a Web page
because you are working within the output setting,
namely an HTML page.
• Traditionally, you had to fragment the output (i.e.
the header, body, footer etc..) and then put it into
the code.
• Now we are inserting the code directly into the
output.

25
The use of include()
• Besides breaking up PHP code into multiple blocks, it is also
possible to include code from external files into your pages.
• Sometimes you wish to keep bits of code in its own file - for
instance, HTML code that makes up a repeating element such
as a logo or footer, or PHP code that makes up a function that
you might want to use in several different pages.
• suppose we break out the footer into its own file, and the
initial PHP block into its own file:
setdate.php:
<?php $today=getdate(time());?>
footer.php:
<!-- begin footer --><SMALL>Today is <?php print $today[weekday];?></SMALL>

26
The use of include()…..
• Now, we can use PHP's include() function to pull the above files
into our example page:
<?php
include ("setdate.php");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<?php include ("footer.php");
?>
• The most common use for the include() function is, as seen above,
to reuse certain components across several pages. Files called
by include() can have other extensions like html, php3 and so on.

27
How PHP works
• PHP code resides on a Web server.
• User requests a page (URL) from the Web server.
• Web server executes the PHP code, which dynamically
generates HTML output based on the result of its
computations.
• HTML output is sent to the user (client).
• The (static) HTML process…
– User requests a URL from the Web server.
– Web server sends the exact content of that page (HTML) to the client.

28
PHP syntax
• Start your PHP code with <?php and end it with ?>.
• Alternatively, you can use <? and ?>.
• Every PHP line of code ends with a semicolon.
• Most PHP constructs such as function names are case-
sensitive.
• If most of the page content is HTML, the PHP code is usually
embedded.
• PHP code typically resides in a plaintext file with a .php
extension.
• The code itself is defined within PHP delimiters:
<?php and end ?>.

29
cont…
• The PHP interpreter considers anything outside of these
delimiters as plaintext to be sent to the client.
• A PHP scripting block always starts with <?php and ends
with ?>.
• A PHP scripting block can be placed anywhere in the
document.
• On servers with shorthand support enabled you can start a
scripting block with <? and end with ?>.
• For maximum compatibility, it is recommended to use the
standard form (<?php) rather than the shorthand form.
<?php
?>

30
cont…
• A PHP file normally contains HTML tags, just like an
HTML file, and some PHP scripting code.
• Below, we have an example of a simple PHP script
which sends the text "Hello World" to the browser:
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>

31
cont….
• Each code line in PHP must end with a semicolon.
• The semicolon is a separator and is used to
distinguish one set of instructions from another.
• There are two basic statements to output text with
PHP: echo and print.
• In the example above we have used the echo
statement to output the text "Hello World".
Note: The file must have a .php extension. If the file has
a .html extension, the PHP code will not be executed.

32
Example
<html>
<head><title>Hello World in PHP</title></head>
<body>
<?php //this is a comment in PHP, yes just like in Java
// <?php indicates the start of PHP directives in HTML
echo "Hello World, ".$_ENV["USERNAME"];
// our Hello World with your username
//Finally terminate the PHP directives
?>
</body>
</html>

33
Cont…
Now the code you see to the previous slide resides on the web
server.
• The user on the PC never sees this code.
• Rather the HTTP web server detects the <?php ... ?> directives
and passes this code onto the PHP interpreter.
• Depending on the contents of the directives code, the PHP
interpreter links to databases, other code, and/or other
services and then generates the final HTML code which is
transmitted to the requesting web browser and displayed
there.
• So, PHP can be thought of as a program generator using
basic HTML templates as the skeleton.

34
Cont…
Here is the details on how the process works.
• The first three lines are just standard HTML and the PHP
interpreter just passes them through unchanged.
• The next line is the PHP tag signalled by the <?php opening
marker.
• This signals to the PHP interpreter that its code follows until
the closing ?> marker is found.
• the period, "." acts a concatenation operator in PHP.
• It tells PHP to add on to the end of " Hello World, " the value
of the $_ENV["USERNAME"] variable.
• PHP comes with several hundred predefined variables and
functions.
35
cont….
• Most of the predefined variables are associated with
web user, the web server and the parameters of the
session they are conducting.
• One of those predefined variable is
$_ENV["USERNAME"] - which is the username of the
PC client.
• Actually, this is not just a variable, but an array
variable, hence the brackets, [...].
• But it is not an ordinary array; but rather an
associative array - hence the string, "USERNAME", is
used as an index into the array, $_ENV. (will be
discussed in the array section).
36
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.
1. Upload your .php file to your Web account (i.e., within
the www-home directory).
2. Make sure the permissions are set correctly;
3. Navigate to the file with a Web browser.

37
Cont….
The process happening behind the scenes is as follows:
1. You (the client) are requesting the URL
2. The Web server is configured to associate any filename
ending in .php with the PHP interpreter. The PHP
interpreter opens the file and begins processing it.
3. The output of the PHP interpreter is sent to the client.

38
Cont...
• The PHP processor has two modes: copy (HTML) and
interpret (PHP).
• PHP processor takes a PHP document as input and
produces an HTML document file
• When it finds HTML code in the input file, simply
copies it to the output file
• When it finds PHP script, it interprets it and send any
output of the script to the output file
• This new output file is sent to the requesting browser.
• The client never sees the PHP script.

39
40
General Syntactic Characteristics
• PHP code can be specified in an HTML document
internally or externally:
– Internally:
<?php
...
?>
– Externally: include ("myScript.inc")
• The included file can contain HTML or client-side
script as well as PHP
• If the file has PHP, the PHP must be in <?php ... ?>,
even if the include appears in <?php ... ?>
41
Basic PHP Facts
• Like JS, PHP is usually purely interpreted
• Syntax and semantics are closely related to JS
• Like JS, PHP uses dynamic typing
• Variables are not declared, they have intrinsic
type
• Every statement ends in a ;
• PHP variables are case sensitive, but reserved
words and function names are not.
– (Ex)
• while, WHILE, While, and wHiLe are same
42
43
Comments in PHP
• In PHP, three different kinds (Java and Perl)
(a) // ... ; for single line
(b) # ... ; for single line
(c) /* ... */ ; for multiple-line
• <html>
<body>
<?php
//This is a comment

/*
This is
a comment
block
*/
?>
</body>
</html>

44
The Script Tags
– All PHP code is contained in one of several script
tags:
1. <?php
// Some code here
?>

2. <?
// Some code
?>

3. <script language=“PHP">
// Some code here
</script>
45
PHP variables
• A variable is a holder for a type of data.
• A variable can hold numbers, strings, booleans, objects, resources or it can
be NULL.
• The syntax for PHP variables is similar to C and most other programming
languages. Like C++ and Java.
• Variables do not need to be declared before being used. They are
dynamically typed, so you do not need to specify the type (e.g., int, float,
etc.).
• A variable's type does not have to be fixed, meaning it can be changed over
the variable's lifetime. It will automatically be declared when a value is
assigned to it.
• Variables are BOUND or UNBOUND
– Unbound variables have the value NULL
– Type information is obtained from the current bound value

46
PHP Variable Naming Conventions
There are a few rules that you need to follow when choosing a
name for your PHP variables.
– In PHP all the variables begin with a dollar sign "$" and the
value can be assigned using the "=" operator.
– The dollar sign is not technically part of the variable name,
but it is required as the first character for the PHP parser to
recognize the variable as such. e.g. ($Name).
– PHP variables must start with a letter or underscore "_".
– PHP variables may only be comprised of alpha-numeric
characters and underscores. a-z, A-Z, 0-9, or _ .
– Variables with more than one word should be separated
with underscores: $my_variable.
– Variables with more than one word can also be
distinguished with capitalization: $myVariable.

47
Variable References
• PHP also allows you to do some neat things with
variables.
• It allows you to create aliases for variables, and it
also allows you to have variables whose name is a
variable.
• A variable reference, or alias, is a variable assigned
to refer to the same information as another
variable.
• To assign an alias to a variable, you use the
reference operator, which is an equals sign
followed by an ampersand.
48
Cont...
The following code snippet outputs: 'Have a nice day!' twice:

<?php
$firstVar = 'nice day!'; //Assign the value 'nice day!' to $firstVar
$secondVar = &$firstVar; // Reference $firstVar via $secondVar.
$secondVar = "Have a $secondVar"; // Alter $secondVar...
echo $firstVar;
echo $secondVar;
?>

49
Environment/predefined Variables
• Beyond the variables you declare in your code, PHP has
a collection of environment variables, which are system
defined variables that are accessible from anywhere
inside the PHP code.
• These variables allow the script access to server
information, form parameters, environment
information, etc
• 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.

50
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).

51
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).

52
Cont...
• $_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 (which is still available,
but deprecated).

53
Cont...
• The code to use the environment variables will be as
follows:
• <?php
// moderate shortcut
$newVar = $_COOKIE["myFirstCookie"];

// full version
$newVar = $HTTP_COOKIE_VARS["myFirstCookie"];
?>

54
Php constants
• What is Constant in PHP?
• A constant is a name or an identifier for a fixed value.
• Constant are like variables, except that once they are defined,
they cannot be undefined or changed
• What is Magic Constants?
• Moreover PHP provides a set of special predefined constants
that change depending on where they are used.
• These constants are called magic constants
• Magic constants begin with two underscores and end with two
underscores
• __LINE__
55
<?php
• echo "Line number " . __LINE__ . "<br>"; //
Displays: Line number 2
• echo "Line number " . __LINE__ . "<br>"; //
Displays: Line number 3
• echo "Line number " . __LINE__ . "<br>"; //
Displays: Line number 4
?>
Output
Line number 2
Line number 3
Line number 4 56
• __FILE__
• The __FILE__ constant returns full path and name of the PHP file that's being
executed
<?php
// Displays the absolute path of this file echo "The full path of this file is: " .
__FILE__;
?>
Output
The full path of this file is: C:\wamp\www\IT-Class\Magic.PHP
__DIR__
• The __DIR__ constant returns the directory of the file
<?php
// Displays the directory of this file echo "The directory of this file is: " . __DIR__;
?>
OUTPUT
The directory of this file is: C:\wamp\www\IT-Class 57
__FUNCTION__
• The __FUNCTION__ constant returns the name of
the current function.
<?php
function myFunction()
{ echo "The function name is - " .
__FUNCTION__;}myFunction();
// Displays: The function name is – myFunction
?>
__CLASS__
• The __CLASS__ constant returns the name of the
current class 58
Data Types
1. Scalar types
• Boolean, integer, float, double, string

2. Compound types
• Array, object

3. Special types
• Resource, null

59
Here are the fundamental variable types.
• Numeric
– integer. Integers (±2 raised 31); 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. Also as
in C, 0 (zero) is false and anything else is true.
• string. String of characters.
• array. An array of values, possibly other arrays.
Arrays can be indexed or associative (i.e., a hash
map).
• object. Similar to a class in C++ or Java.
60
Cont…
• Resource:
• A handle to something that is not PHP data (e.g., image
data, database query result).
• Or in other words, Resource is to represent a PHP
extension resource (e.g. Database query, open file,
database connection, etc). You will never directly touch
this type, it will be passed to the relevant functions that
know how to interact with the specified resource.
• 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;
61
Cont....
• PHP has a useful function named
var_dump() that prints the current type and
value for one or more variables.
• Arrays and objects are printed recursively
with their values indented to show
structure.
$a = 35;
$b = "Programming is fun!";
$c = array(1, 1, 2, 3);
var_dump($a,$b,$c);

62
Here’s the output from the above code.

int(35)
string(19) "Programming is fun!"
array(4) {
[0]=> int(1)
[1]=>int(1)
[2]=>int(2)
[3]=>int(3)
}
• The variable $a is an integer with value 35.
• The variable $b is a string that contains 19
characters.
• The variable $c is an array with 4 elements: element
zero is an integer whose value is 1, and so on.
63
Examples:
• In the following example, four variables are
automatically declared by assigning a value to them:
<?php
$number = 5;
$string1 = "this is a string\n";
$string2 = 'this is another "string"';
$real = 37.2;
$welcome=”Hello and welcome to my website.”;
$numvisitor=27;
$welcome=83;
?>

64
PHP Strings
• They are sequences of characters, like "PHP
supports string operations".
– NOTE: Built-in string functions is given in function
reference PHP String Functions
Visit www.php.net
• Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted
string";
$string_39 = "This string has thirty-nine characters";
$string_0 = “ "; // a string with zero characters

65
Strings ......
• Singly quoted strings are treated almost literally,
whereas doubly quoted strings replace variables with
their values as well as specially interpreting certain
character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce following result:
My $variable will not print!\n
My name will print
66
Strings…..
• In PHP, a string is anything between matching quotes:
'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 (").
• For example, if you start a string with double quotes, then only
double quote marks are important to the parser.

67
Strings…..
• You can include single quote marks or
whatever other characters you wish in the
double quoted string. So, these strings work
correctly in PHP:

$s = "I am a 'single quote string' inside a double quote string";


$s = 'I am a "double quote string" inside a single quote string';

68
Strings.....
• There are no artificial limits on string length - within
the bounds of available memory, you ought to be
able to make arbitrarily long strings.
• Strings that are delimited by double quotes (as in
"this") are preprocessed in both the following two
ways by PHP:
• Certain character sequences beginning with
backslash (\) are replaced with special characters
• Variable names (starting with $) are replaced with
string representations of their values.

69
String Concatenation Operator
• To concatenate two string variables together, use the dot
(.) operator:
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
• This will produce following result:
Hello World 1234
• If we look at the code above you see that we used the
concatenation operator two times. This is because we had
to insert a third string.
• Between the two string variables we added a string with a
single character, an empty space, to separate the two
variables.
70
Using the strlen() function
• The strlen() function is used to find the length of a
string.
• Let's find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>

• This will produce following result:


12

• The length of a string is often used in loops or other


functions, when it is important to know when the
string ends. (i.e. in a loop, we would want to stop
the loop after the last character in the string)
71
Using the strpos() function
• The strpos() function is used to search for a string or character within
a string.
• 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.
• Let's see if we can find the string "world" in our string:
<?php
echo strpos("Hello world!","world");
?>
• This will produce following result:
6
• As you see the position of the string "world" in our string is position
6. The reason that it is 6, and not 7, is that the first position in the
string is 0, and not 1.

72
PHP Arrays
• An array is a data structure that stores one or more similar
type of values in a single value.
– For example if you want to store 100 numbers then instead
of defining 100 variables its easy to define an array of 100
length.
• There are three different kind of arrays and each array value is
accessed using an ID which is called array index.
– Numeric 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 array - An array containing one or more arrays and
values are accessed using multiple indices
• NOTE: Built-in php array functions are found in www. php.net

73
Numeric Array
• These arrays can store numbers, strings and
any object but their index will be
prepresented by numbers. By default array
index starts from zero.
Example
• Following is the example showing how to
create and access numeric arrays.
• Here we have used array() function to
create array.

74
<html><body> $numbers[1] = "two";
<?php $numbers[2] = "three";
/* First method to create $numbers[3] = "four";
array. */ $numbers[4] = "five";
$numbers = array( 1, 2, 3, 4, 5); foreach( $numbers as $value )
foreach( $numbers as $value ) {
{ echo "Value is $value <br />";
echo "Value is $value <br/>"; }
} ?>
/* Second method to create </body></html>
array. */
$numbers[0] = "one";

75
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

76
Associative Arrays
• The associative arrays are very similar to numeric arrays in
term of functionality but they are different in terms of their
index.
• 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.
– NOTE: Don't keep associative array inside double quote while
printing otherwise it would not return any value.

77
Example
<html><body>
<?php
/* First method to associate create array. */
$salaries = array(
"mohammad" => 2000,
"qadir" => 1000,
"zara" => 500
);
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

78
/* Second method to create array. */
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
echo "Salary of mohammad is ". $salaries['mohammad']
. "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body></html>

79
Cont.....
This will produce following result:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

80
Multidimensional Arrays
• A multi-dimensional 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.
Example
• In this example we create a two dimensional array to
store marks of three students in three subjects:
• This example is an associative array, you can create
numeric array in the same fashion.

81
<html><body> "zara" => array
(
<?php
"physics" => 31,
$marks = array( "maths" => 22,
"mohammad" => array "chemistry" => 39
( )
"physics" => 35, );
/*Accessing multi-dimensional array values
"maths" => 30, */
"chemistry" => 39 echo "Marks for mohammad in physics : " ;
), echo $marks['mohammad']['physics'] .
"qadir" => array "<br />";
echo "Marks for qadir in maths : ";
( echo $marks['qadir']['maths'] . "<br />";
"physics" => 30, echo "Marks for zara in chemistry : " ;
"maths" => 32, echo $marks['zara']['chemistry'] . "<br />";
?> </body></html>
"chemistry" => 29
),
82
This will produce following result:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39

83
Arrays….
We can even mix the two if we'd like

– PHP arrays are a cross between numbered


arrays and associative arrays.
– This means that you can use the same syntax
and functions to deal with either type of array,
including arrays that are:
• Indexed from 0
• Indexed by strings
• Indexed with non-continuous numbers
• Indexed by a mix of numbers and strings

84
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], $array2["one"], $array3[6]);
?>

85
Arrays….
• From the above example, the indices in the array1 are
implicit, while the indices in array2 are explicit.
• When specifically setting the index to a number N with
the =>operator, the next value has the index N+1 by default.
• Explicit indices do not have to be listed in sequential order.
You can also mix numerical and string indexes, but it is not
recommended.
• Assigning a collection of values to an array variable is simple
using the array() construct:
• $colors = array("blue","indigo","yellow");
• Or, if you know that you want to create an array $colors but don't
yet know what values to fill it with, create an empty array:
• $colors = array();

86
Arrays….
• Adding new values to the array is a breeze:
– $colors[] = "hunter green";

• Now the array $colors contains four values.


• Often times, you need to access a single item in an array, such
as for output or a calculation.
• To do this, we can output the second color in the array via the
key 1: print $colors[1];
...will output indigo.
– Next, it makes sense to use keys which are labels more meaningful
than a mere index (if you describe for example the car):
$colors = array("exterior"=>"blue",
• "trim"=>"indigo",
• "fabric"=>"yellow",
• "dashboard"=>"hunter green");

87
Arrays….
• It's now easy to output the fabric color of this car,
because fabric is a key in the list:
– print $colors[fabric];
...will output yellow.
• Next, we wanted to output each of the items in $colors, along
with the key associated with that item.
• These returned values are assigned on-the-fly to $key
and $value.
foreach ($colors as $key=>$value) {
print "$colors[\"$key\"]== $value<br>"; }
• The similar result is courtesy of the list() function:
while (list($key,$value) = each($colors)) {
print "$key: $value<BR>"; }
88
Arrays….
• In the browser, the above code would output:
exterior: blue
trim: indigo
fabric: yellow
dashboard: hunter green
• Simply, use PHP's ksort() function to sort $colors by key, and
then step through the array as before:
ksort ($colors);
while (list($key,$value) = each($colors)) {
print "$key: $value<BR>"; }

89
Arrays….
• There are various predefined sort functions in
PHP
 sort (rsort for reverse)
• Sorts arrays of numbers numerically
• Sorts arrays of strings alphabetically
• If mixed, the strings count as 0
• Reindexes array so that keys start at 0 and increment from
there
 asort
• Same as sort but retains the original key values (arsort for
reverse)
90
PHP Control Structures
if, while, do, for, switch are virtually identical to those in C++ and
Java
PHP Decision Making
The if, elseif ...else and switch statements are used to take
decision based on the different condition.
1. if...else statement - use this statement if you want to execute a
set of code when a condition is true and another if the
condition is not true
2. elseif statement - is used with the if...else statement to
execute a set of code if one of several condition are true
3. switch statement - is used if you want to select one of many
blocks of code to be executed, use the Switch statement. The
switch statement is used to avoid long blocks of if..elseif..else
code.

91
If …else statement
Normal if..then..else statement
• Ex.
if ($a<5) {
$b=$a+10;
}
else {
$b=$a*2;
}

92
If...elseif... else statement
The example below introduces these constructs:
<?php
// Conditionals
if ($a) {
print "a is true<BR>\n";
}
elseif ($b) {
print "b is true<BR>\n";
}
else
{
print "neither a or b is true<BR>\n";
}
93
The Switch Statement
• If you want to select one of many blocks of code to be executed, use
the Switch statement.
• The switch statement is used to avoid long blocks of if..elseif..else code.
• Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed if expression is different from both label1 and label2;
}

94
Example
 The switch statement works in an unusual way.
 First it evaluates given expression then seeks a label
to match the resulting value.
 If a matching value is found then the code
associated with the matching label will be executed
or if none of the labels match then statement will
execute any specified default code.

95
case "Thu":
<html><body>
echo "Today is Thursday";
<?php
break;
$d=date("D");
case "Fri":
switch ($d)
echo "Today is Friday";
{
break;
case "Mon":
case "Sat":
echo "Today is Monday";
echo "Today is Saturday"; break;
break;
case "Sun":
case "Tue":
echo "Today is Sunday";
echo "Today is Tuesday";
break;
break;
default:
case "Wed":
echo "Wonder which day is this ?“;
echo "Today is Wednesday";
}
break;
?>
</body></html>
96
PHP Control Structures….
// Loops
do {
$c = test_something();
} while ($c);
while ($d) {
print "ok<BR>\n";
$d = test_something();
}
for ($i = 0; $i < 10; $i++) {
print "i=$i<BR>\n";
}
?>
97
PHP Control Structures…..
For loop
for (starting value;ending value;increment)
{
Statements
}
– Ex.
for ($i=0; $i<10; $i++)
{
echo $i;
}

98
PHP Control Structures….
While Loop

while (something is true)


{
some statements
}
Ex.
$i=0;
while ($i<10){
echo $i;
$i++;
}

99
PHP Expressions and Operators
 Similar to those in C++ / Java / Perl
 Be careful with a few operators
• / in PHP is always floating point division
– To get integer division, we must cast to int
$x = 15;
$y = 6;
echo ($x/$y), (int) ($x/$y), "<BR />";
» Output is 2.5 2

100
PHP operators
Operator Meaning
== Is Equal to
!= Not Equal to
< Is less than
<= Is less than or equal to
> Is Greater than
>= Is Greater than or equal to
&& and And
|| or Or
101

You might also like