You are on page 1of 156

Copyright IBM Corporation 2012

PHP-Basics
Copyright IBM Corporation 2012
2
Requesting a Static HTML Document
Client
Server
<html>
<head></head>
<body>



</html>
Static HTML files
GET /index.html HTTP/1.0
User-Agent: Mozilla/4.51 [en]...
Host: sirah.csit.fsu.edu:8080
Accept: image/gif, ..., */*
...
HTTP/1.1 200 OK
Content-type: text/html
<html>
<head>...</head>
<body>
...

</html>
HTTP Request
HTTP Response
Copyright IBM Corporation 2012
Dynamic Web pages
Applications executed by the server at run-time
to process client input or generate document in
response to client request
Generating dynamic Web pages requires
programming

Copyright IBM Corporation 2012
4
Dynamic Generation of HTML
Client
Server
GET /hello.pl?who=bryan HTTP/1.0
User-Agent: Mozilla/4.51 [en]...
Host: sirah.csit.fsu.edu:8080
Accept: image/gif, ..., */*
...
HTTP/1.1 200 OK
Content-type: text/html
<html>
<body>
Hello bryan!
</body></html>
HTTP Request
HTTP Response
#!/usr/bin/perl
$name = param(who) ;
print Content-type: text/html\n\n ;
print <html><body>Hello $name!</body></html>\n ;
Script, or method
Copyright IBM Corporation 2012
Scripts: Server-Side VS Client-
Side
Server-side
the first type possible on the Web
action occurs at the server
Client-side
generally easier to implement
may be prepared and implemented offline
action occurs on the client side (browser)

Copyright IBM Corporation 2012
Client-Side Scripting
Client side scripts are embedded inside HTML document.
They are interpreted by browser.
When Web browser encounters a script, it calls a scripting
interpreter, which parses and deciphers the scripting code.
Provide response to questions and queries without
interventions from the server
Validate user data
Calculate expressions
Link to other applications
Copyright IBM Corporation 2012
PHP == Hypertext Preprocessor
Open-source, server-side scripting language
Used to generate dynamic web-pages
PHP scripts reside between reserved PHP
tags
This allows the programmer to embed PHP
scripts within HTML pages
What is PHP?
Copyright IBM Corporation 2012
What is PHP (contd)
Interpreted language, scripts are parsed at run-
time rather than compiled beforehand
Executed on the server-side
Source-code not visible by client
View Source in browsers does not display
the PHP code
Various built-in functions allow for fast
development
Compatible with many popular databases
Copyright IBM Corporation 2012
PHP's Place in the Web World
PHP is a programming language that's used
mostly for building web sites.
Instead of a PHP program running on a desktop
computer for the use of one person, it typically
runs on a web server and is accessed by lots of
people using web browsers on their own
computers.
This section explains how PHP fits into the
interaction between a web browser and a web
server.
Copyright IBM Corporation 2012
PHP's Place in the Web World
When you sit down at your computer and pull
up a web page using a browser such as Internet
Explorer or Mozilla, you cause a little
conversation to happen over the Internet
between your computer and another computer.

Copyright IBM Corporation 2012
PHP's Place in the Web World
Here's what's happening in the numbered steps
of the diagram:
You type www.example.com/catalog.html into
the location bar of Internet Explorer.
Internet Explorer sends a message over the
Internet to the computer named
www.example.com asking for the/catalog.html
page.
Apache, a program running on the example.com
computer,gets the message and reads the
catalog.html file from the disk drive.
Copyright IBM Corporation 2012
PHP's Place in the Web World
Apache sends the contents of the file back to
your computer over the Internet as a response to
Internet Explorer's request.
Internet Explorer displays the page on the
screen, following the instructions of the HTML
tags in the page.
Every time a browser asks for
example.com/catalog.html, the web server sends
back the contents of the samecatalog.html file.
The only time the response from the web server
changes is if someone edits the file on the server
Copyright IBM Corporation 2012
PHP's Place in the Web World
Here's what's happening in the numbered steps of the
PHP-enabled conversation:
You type example.com/catalog/yak.php into the location
bar of Internet Explorer.
Internet Explorer sends a message over the Internet to
the computer named example.com asking for the
/catalog/yak.php page.
Apache, a program running on the example.com
computer, gets the message and asks the PHP
interpreter,another program running on the example.com
computer, "What does /catalog/yak.php look like?"
Copyright IBM Corporation 2012
PHP's Place in the Web World
The PHP interpreter runs the commands in
yak.php, possibly exchanging data with a
database program such as MySQL.
The PHP interpreter takes the yak.php program
output and sends it back to Apache as an
answer to "What does/catalog/yak.php look
like?"
Apache sends the page contents it got from the
PHP interpreter back to your computer over the
Internet in response to Internet Explorer's
request.
Copyright IBM Corporation 2012
PHP Is Free (as in Money)
You don't have to pay anyone to use PHP.
Whether you run the PHP interpreter on a
beat-up 10-year-old PC in your basement or in
a room full of million-dollar "enterprise-class"
servers, there are no licensing fees, support
fees,maintenance fees, upgrade fees, or any
other kind of charge.
Copyright IBM Corporation 2012
PHP Is Free (as in Speech)
As an open source project, PHP makes its
innards available for anyone to inspect.
If it doesn't do what you want, or you're just
curious about why a feature works the way it
does.you can poke around in the guts of the
PHP interpreter (written inthe C programming
language) to see what's what.
Even if you don't have the technical expertise
to do that, you can get someone who does to do
the investigating for you.
Copyright IBM Corporation 2012
PHP Is Cross-Platform
You can use PHP with a web server computer
that runs Windows, Mac OS X, Linux, Solaris,
and many other versions of Unix.
if you switch web server operating systems,
you generally don't have to change any of your
PHP programs.
Just copy them from your Windows server to
your Unix server, and they will still work.
Copyright IBM Corporation 2012
PHP Is Widely Used
As of March 2004, PHP is installed on more
than 15 million different web sites, from
countless tiny personal home pages to giants
like Yahoo!.
There are many books, magazines, and web
sites devoted to teaching PHP and exploring
what you can do with it.
There are companies that provide support and
training for PHP.
In short, if you are a PHP user, you are not
alone
Copyright IBM Corporation 2012
PHP Hides Its Complexity
You can build powerful e-commerce engines in
PHP that handle millions of customers.
You can also build a small site that
automatically maintains links to a changing list
of articles or press releases.
When you're using PHP for a simpler project, it
doesn't get in your way with concerns that are
only relevant in a massive system.

Copyright IBM Corporation 2012
PHP Hides Its Complexity
When you need advanced features such as
caching, custom libraries, or dynamic image
generation, they are available.
If you don't need them, you don't have to worry
about them.
You can just focus on the basics of handling
user input and displaying output.
Copyright IBM Corporation 2012
PHP Is Built for Web Programming
Unlike most other programming languages,
PHP was created from the ground up for
generating web pages.
This means that common web programming
tasks, such as accessing form submissions and
talking to a database, are often easier in PHP.
PHP comes with the capability to format
HTML, manipulate dates and times, and
manage web cookies tasks that are often
available only as add-on libraries in other
programming languages.
Copyright IBM Corporation 2012
HTML EMBEDDING
<HTML>
<HEAD>Sample PHP Script</HEAD>
<BODY>
The following prints "Hello, World":
<?php
print "Hello, World";
?>
</BODY>
</HTML>
Copyright IBM Corporation 2012
COMMENTS
You can write comments three different ways:
C way
/* This is a C like comment
* which can span multiple
* lines until the closing tags
*/
C++ way
// This is a C++ like comment which ends at the
end of the line
Copyright IBM Corporation 2012
COMMENTS
Shell way
# This is a shell like comment which ends at the
end of the line
Copyright IBM Corporation 2012
VARIABLES
Variables in PHP are quite different from
compiled languages such as C and Java.
This is because their weakly typed nature,
which in short means you dont need to declare
variables before using them.
you dont need to declare their type and, as a
result, a variable can change the type of its
value as much as you want.
Copyright IBM Corporation 2012
VARIABLES
Variables in PHP are preceded with a$ sign,
and similar to most modern languages.
they can start with a letter (A-Z a-z)
or_(underscore) and can then contain as many
alphanumeric characters and underscores as
you like.
Examples of legal variable names include
$count
$_Obj
$A123
Copyright IBM Corporation 2012
VARIABLES
Example of illegal variable names include
$123
$*ABC
As previously mentioned, you dont need to
declare variables or their type before using
them in PHP. The following code example uses
variables:
$PI = 3.14;
$radius = 5;
$circumference = $PI * 2 * $radius;
Copyright IBM Corporation 2012
Indirect References to Variables
An extremely useful feature of PHP is that you
can access variables by using indirect
references, or to put it simply, you can create
and access variables by name at run time.
Consider the following example:
$name = "John";
$$name = "Registered user";
print $John;
This code results in the printing of"Registered
user."
Copyright IBM Corporation 2012
Managing Variables
Three language constructs are used to manage
variables.
They enable you to check if certain variables
exist, remove variables, and check variables
truth values.

Copyright IBM Corporation 2012
Managing Variables
isset()
determines whether a certain variable has already
been declared by PHP. It returns a boolean value
true.
if the variable has already been set, and false
otherwise, or if the variable is set to the value
NULL.
Consider the following script:
if (isset($first_name)) {
print '$first_name is set';}
Copyright IBM Corporation 2012
Managing Variables
unset()
undeclares a previously set variable, and
frees any memory that was used by it if no
other variable references its value.
A call to isset() on a variable that has been
unset() returns false.

Copyright IBM Corporation 2012
Managing Variables
For example:
$name = "John Doe";
unset($name);
if (isset($name)) {
print $name is set';
}
This example will not generate any output,
because isset() returns false.
Copyright IBM Corporation 2012
Managing Variables
empty() may be used to check if a variable has
not been declared or its value is false.
This language construct is usually used to
check if a form variable has not been sent or
does not contain data.
When checking a variables truth value, its
value is first converted to a Boolean according
to the rules in the following section, and then it
is checked for true/false.
Copyright IBM Corporation 2012
Managing Variables
For example:
if (empty($name)) {
print 'Error: Forgot to specify a value for
$name';
}
This code prints an error message if $name
doesnt contain a value that evaluates to true.
Copyright IBM Corporation 2012
DATA TYPES
Eight different data types exist in PHP, five of
which are scalar and each of the remaining
three has its own uniqueness.
The previously discussed variables can contain
values of any of these data types without
explicitly declaring their type.
The variable behaves according to the data
type it contains.
Copyright IBM Corporation 2012
Integers
Integers are whole numbers and are equivalent
in range as your C compilers long value.
On many common machines, such as Intel
Pentiums, that means a 32-bit signed integer
with a range between 2,147,483,648 to
+2,147,483,647.
Integers can be written in decimal,
hexadecimal (prefixed with 0x), and octal
notation (prefixed with 0), and can include +/-
signs.
Copyright IBM Corporation 2012
Integers
Some examples of integers include
240000
0xABCD
007
-100
Copyright IBM Corporation 2012
Floating-Point Numbers
Floating-point numbers (also known as real
numbers) represent real numbers and are
equivalent to your platform C compilers
double data type.
On common platforms, the data type size is 8
bytes and it has a range of approximately
2.2E308 to 1.8E+308.
Floating-point numbers include a decimal
point and can include a +/- sign and an
exponent value.
Copyright IBM Corporation 2012
Floating-Point Numbers
Examples of floating-point numbers include
3.14
+0.9e-2
-170000.5
54.6E42
Copyright IBM Corporation 2012
Strings
Strings in PHP are a sequence of characters
that are always internally null terminated.
However, unlike some other languages, such
as C, PHP does not rely on the terminating null
to calculate a strings length, but remembers its
length internally.
When writing string values in your source
code, you can use double quotes ("), single
quotes (') or here-docs to delimit them.
Copyright IBM Corporation 2012
Double Quotes
Examples for double quotes:
"PHP: Hypertext Pre-processor"
"GET / HTTP/1.0\n"
"1234567890"
Strings can contain pretty much all characters.
Some characters cant be written as is,
however, and require special notation:
Copyright IBM Corporation 2012
Double Quotes
Strings can contain pretty much all characters.
Some characters cant be written as is,
however, and require special notation:

Copyright IBM Corporation 2012
Single Quotes
In addition to double quotes, single quotes
may also delimit strings.
The following table includes the only two
escapings supported by single quotes:
Examples:
'Hello, World'
'Today\'s the day'

Copyright IBM Corporation 2012
Here-Docs
Here-docs enable you to embed large pieces
of text in your scripts, which may include lots
of double quotes and single quotes, without
having to constantly escape them.
The following is an example of a here-doc:
<<<THE_END
PHP stands for "PHP: Hypertext
Preprocessor".The acronym "PHP" is
therefore, usually referred to as a recursive
acronym
THE_END
Copyright IBM Corporation 2012
Booleans
PHP automatically converts types when
needed.
Boolean is probably the type that other types
are most often converted to behind the scenes.
This is because, in any conditional code such
as if statements,loops, and so on, types are
converted to this scalar type to check if the
condition is satisfied.
Copyright IBM Corporation 2012
Booleans
Consider the following code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator == 0) {
print "The denominator needs to be a non-zero
number\n";
}
Copyright IBM Corporation 2012
NULL
Null is a data type with only one possible
value: the NULL value.
It marks variables as being empty, and its
especially useful to differentiate between the
empty string and null values of databases.
The isset($variable) operator of PHP returns
false for NULL, and true for any other data
type, as long as the variable youre testing
exists.
The following is an example of using NULL:
$value = NULL;
Copyright IBM Corporation 2012
Constants
In PHP, you can define names, called constants,
for simple values.
As the name implies, you cannot change these
constants once they represent a certain value.
The names for constants have the same rules as
PHP variables except that they dont have the
leading dollar sign.
Copyright IBM Corporation 2012
Constants
Unlike variables, constants, once defined, are
globally accessible.
You dont have to (and cant) redeclare them in
each new function and PHP file.
To define a constant, use the following
function:
define("CONSTANT_NAME", value [,
case_sensitivity])

Copyright IBM Corporation 2012
OPERATORS
PHP contains three types of operators: unary
operators, binary operators, and one ternary
operator.
Binary operators are used on two operands:
2 + 3
14 * 3.1415
$i 1
These examples are also simple examples of
expressions.

Copyright IBM Corporation 2012
OPERATORS
PHP can only perform binary operations on
two operands that have the same type.
However, if the two operands have different
types, PHP automatically converts one of them
to the others type, according to the following
rules.

Copyright IBM Corporation 2012
Numeric Operators
All the binary operators (except for the
concatenation operator) work only on numeric
operands.
If one or both of the operands are strings,
Booleans, nulls, or resources, they are
automatically converted to their numeric
equivalents before the calculation is performed
(according to the previous table).
Copyright IBM Corporation 2012
Numeric Operators
Copyright IBM Corporation 2012
Concatenation Operator
The concatenation operator concatenates two
strings. This operator works only on strings;
thus, any non-string operand is first converted
to one.
The following example would print out "The
year is 2000":
$year = 2000;
print "The year is " . $year;
The integer $year is internally converted to the
string "2000" before it is concatenated with the
strings prefix, "The year is".
Copyright IBM Corporation 2012
Assignment Operators
Assignment operators enable you to write a
value to a variable.
The first operand (the one on the left of the
assignment operator or l value) must be a
variable. The value of an assignment is the
final value assigned to the variable;
for example, the expression $var = 5 has the
value 5 (and assigns 5 to $var).
Copyright IBM Corporation 2012
Assignment Operators
In addition to the regular assignment operator
=, several other assignment operators are
composites of an operator followed by an equal
sign.
These composite operators apply the operator
taking the variable on the left as the first
operand and the value on the right (the r value)
as the second operand, and assign the result of
the operation to the variable on the left.

Copyright IBM Corporation 2012
Assignment Operators
For example:
$counter += 2; // This is identical to $counter =
$counter + 2;
$offset *= $counter;// This is identical to
$offset = $offset *
$counter;
The following list show the valid composite
assignment operators:
+=, -=, *=, /=, %=, ^=, .=, &=, |=, <<=, >>=
Copyright IBM Corporation 2012
By-Reference Assignment Operator
PHP enables you to create variables as aliases
for other variables.
You can achieve this by using the by-reference
assignment operator =&.
After a variable aliases another variable,
changes to either one of them affects the other.

Copyright IBM Corporation 2012
By-Reference Assignment Operator
For example:
$name = "Judy";
$name_alias =& $name;
$name_alias = "Jonathan";
print $name;
The result of this example is
Jonathan
Copyright IBM Corporation 2012
Comparison Operators
Comparison operators enable you to determine
the relationship between two operands.
When both operands are strings, the
comparison is performed lexicographically.
The comparison results in a Boolean value.
For the following comparison operators,
automatic type conversions are performed, if
necessary.
Copyright IBM Corporation 2012
Comparison Operators
Copyright IBM Corporation 2012
Comparison Operators
For the following two operators, automatic
type conversions are not performed and,
therefore, both the types and the values are
compared.

Copyright IBM Corporation 2012
Logical Operators
Logical operators first convert their operands to
boolean values and then perform the respective
comparison.

Copyright IBM Corporation 2012
Bitwise Operators
Bitwise operators perform an operation on the
bitwise representation of their arguments.
Unless the arguments are strings, they are
converted to their corresponding integer
representation, and the operation is then
performed.
In case both arguments are strings, the
operation is performed between corresponding
character offsets of the two strings (each
character is treated as an integer).
Copyright IBM Corporation 2012
Bitwise Operators
Copyright IBM Corporation 2012
Negation Operators
Negation operators appear before their operand
for example, !$var (! is the operator, $var is the
operand).

Copyright IBM Corporation 2012
Increment/Decrement Operators
Increment/decrement operators are unique in
the sense that they operate only on variables
and not on any value.
The reason for this is that in addition to
calculating the result value, the value of the
variable itself changes as well.

Copyright IBM Corporation 2012
Increment/Decrement Operators
As you can see from the previous table, theres
a difference in the value of post- and pre-
increment. However, in both cases, $var is
incremented by 1.
The only difference is in the value to which the
increment expression evaluates.
Example 1:
$num1 = 5;
$num2 = $num1++;// post-increment, $num2 is
assigned $num1's original value

Copyright IBM Corporation 2012
Increment/Decrement Operators
print $num1; // this will print the value of
$num1, which is now 6
print $num2; // this will print the value of
$num2, which is the
original value of $num1, thus, 5
Example 2:
$num1 = 5;
$num2 = ++$num1;// pre-increment, $num2 is
assigned $num1's incremented value

Copyright IBM Corporation 2012
Increment/Decrement Operators
print $num1; // this will print the value of
$num1, which is now 6
print $num2; // this will print the value of
$num2, which is the
same as the value of $num1, thus, 6
The same rules apply to pre- and post-
decrement.
Copyright IBM Corporation 2012
String Manipulation
The strtoupper() function converts a string to
uppercase.
Example
<?php
echo strtoupper("Hello WORLD!");
?>
The output of the code above will be:
HELLO WORLD!

Copyright IBM Corporation 2012
String Manipulation
The strtolower() function converts a string to
lowercase.
Example
<?php
echo strtolower("Hello WORLD.");
?>
The output of the code above will be:
hello world.

Copyright IBM Corporation 2012
String Manipulation
The ucfirst() function converts the first
character of a string to uppercase.
Example
<?php
echo ucfirst("hello world");
?>
The output of the code above will be:
Hello world

Copyright IBM Corporation 2012
String Manipulation
The ucwords() function converts the first
character of each word in a string to uppercase.
Example
<?php
echo ucwords("hello world");
?>
The output of the code above will be:
Hello World

Copyright IBM Corporation 2012
String Manipulation
The strncmp() function compares two strings.
This function returns:
0 - if the two strings are equal
<0 - if string1 is less than string2
>0 - if string1 is greater than string2


Copyright IBM Corporation 2012
String Manipulation
Example
<?php
echo strcmp("Hello world!","Hello world!");
?>
The output of the code above will be:
0

Copyright IBM Corporation 2012
String Manipulation
The strlen() function returns the length of a
string.
Example
<?php
echo strlen("Hello world!");
?>
The output of the code above will be:
12

Copyright IBM Corporation 2012
String Manipulation
The substr() function returns a part of a string.
Example 1
<?php
echo substr("Hello world!",6);
?>
The output of the code above will be:
world!


Copyright IBM Corporation 2012
String Manipulation
Example 2
<?php
echo substr("Hello world!",6,5);
?>
The output of the code above will be:
world

Copyright IBM Corporation 2012
String Manipulation
The trim() function removes whitespaces and
other predefined characters from both sides of
a string.
Example 1
<html>
<body>
<?php
$str = " Hello World! ";
echo "Without trim: " . $str;
echo "<br />";
echo "With trim: " . trim($str);
?>
<body>
<html>
The browser output of the code above will be:
Without trim: Hello World!
With trim: Hello World!

Copyright IBM Corporation 2012
String Manipulation
Example 2
<?php
$str = "\r\nHello World!\r\n";
echo "Without trim: " . $str;
echo "<br />";
echo "With trim: " . trim($str);
?>
The browser output of the code above will be:
Without trim: Hello World!
With trim: Hello World!

Copyright IBM Corporation 2012
CONTROL STRUCTURES
PHP supports a variety of the most common
control structures available in other
programming languages.
They can be basically divided into two groups:
-conditional control structures
-loop control structures.
Copyright IBM Corporation 2012
CONTROL STRUCTURES
The conditional control structures affect the
flow of the program and execute or skip certain
code according to certain criteria
whereas loop control structures execute certain
code an arbitrary number of times according to
specified criteria.

Copyright IBM Corporation 2012
Conditional Control Structures
Conditional control structures are crucial in
allowing your program to take different
execution paths based on decisions it makes at
runtime.
PHP supports both the if and switch conditional
control structures.

Copyright IBM Corporation 2012
if Statements
if statements are the most common conditional
constructs, and they exist in most programming
languages.
The expression in the if statement is referred to
as the truth expression.
If the truth expression evaluates to true, the
statement or statement list following it are
executed otherwise, theyre not.
Copyright IBM Corporation 2012
if Statements
Syntax
if (expr)
statement
elseif (expr)
statement
elseif (expr)
statement
else
statement
Copyright IBM Corporation 2012
if Statements
You can add an else branch to an if statement
to execute code only if all the truth expressions
in the if statement evaluated to false:
if ($var >= 50) {
print '$var is in range';
}
else {
print '$var is invalid';
}
Copyright IBM Corporation 2012
if Statements
The elseif construct can be used to conduct a
series of conditional checks and only execute
the code following the first condition that is
met.
For example:
if ($num < 0) {
print '$num is negative';
} elseif ($num == 0) {
print '$num is zero';
} elseif ($num > 0) {
print '$num is positive';}
Copyright IBM Corporation 2012
Switch Statements
You can use the switch construct to elegantly
replace certain lengthy if/elseif constructs.
It is given an expression and compares it to all
possible case expressions listed in its body.
When theres a successful match, the following
code is executed, ignoring any further case
lines (execution does not stop when the next
case is reached).
The match is done internally using the
regularequality operator (==), not the identical
operator (===).
Copyright IBM Corporation 2012
Switch Statements
You can use the break statement to end
execution and skip to the code following the
switch construct.
Syntax
switch (expr){
case expr:
statement list
case expr:
statement list
default:
statement list }
Copyright IBM Corporation 2012
Switch Statements
Example
switch ($answer) {
case 'y':
case 'Y':
print "The answer was yes\n";
break;
case 'n':
case 'N':
print "The answer was no\n";
break;
default:
print "Error: $answer is not a valid answer\n";
break;}
Copyright IBM Corporation 2012
While loops
while loops are the simplest kind of loops. In
the beginning of each iteration, the whiles
truth expression is evaluated.
If it evaluates to true, the loop keeps on
running and the statements inside it are
executed.
Copyright IBM Corporation 2012
While loops
For example, heres one possible
implementation of factorial, using a while
loop(assuming $n contains the number for
which we want to calculate the factorial):
$result = 1;
while ($n > 0) {
$result *= $n--;
}
print "The result is $result";
Copyright IBM Corporation 2012
do...while Loops
The do...while loop is similar to the previous
while loop, except that the truth expression is
checked at the end of each iteration instead of
at the beginning.
This means that the loop always runs at least
once.
do {
statement list
if ($error) {
break;}
statement list
} while (false);
Copyright IBM Corporation 2012
do...while Loops
Because do...while loops always iterate at least
one time, the statements inside the loop are
executed once, and only once.
The truth expression is always false. However,
inside the loop body, you can use the break
statement to stop the execution of the
statements at any point, which is convenient.
Of course, do...while loops are also often used
for regular iterating purposes.
Copyright IBM Corporation 2012
for Loops
The start expression is evaluated only once
when the loop is reached.
Usually it is used to initialize the loop control
variable.
The truth expression is evaluated in the
beginning of every loop iteration.
If true, the statements inside the loop will be
executed; if false, the loop ends.

Copyright IBM Corporation 2012
for Loops
The increment expression is evaluated at the
end of every iteration before the truth
expression is evaluated.
Usually, it is used to increment the loop control
variable, but it can be used for any other
purpose as well. Both break and continue
behave the same way as they do with while
loops.
continue causes evaluation of the increment
expression before it re-evaluates the truth
expression.
Copyright IBM Corporation 2012
for Loops
Heres an example:
for ($i = 0; $i < 10; $i++) {
print "The square of $i is " . $i*$i . "\n";
}
The result of running this code is
The square of 0 is 0
The square of 1 is 1
...
The square of 9 is 81
Copyright IBM Corporation 2012
FUNCTIONS
A function in PHP can be built-in or user-
defined.
However, they are both called the same way.
The general form of a function call is
func(arg1,arg2,)
The number of arguments varies from one
function to another.
Each argument can be any valid expression,
including other function calls.

Copyright IBM Corporation 2012
FUNCTIONS
Here is a simple example of a predefined
function:
$length = strlen("John");
strlen is a standard PHP function that returns
the length of a string.
Therefore, $length is assigned the length of the
string "John": four.
Heres an example of a function call being used
as a function argument:
$length = strlen(strlen("John"));

Copyright IBM Corporation 2012
FUNCTIONS
You probably already guessed the result of this
example.
First, the inner strlen("John") is executed,
which results in the integer 4. So, the code
simplifies to
$length = strlen(4);
strlen() expects a string, and therefore (due to
PHPs magical autoconversion between types)
converts the integer 4 to the string "4", and
thus, the resulting value of $length is 1, the
length of "4".

Copyright IBM Corporation 2012
User-Defined Functions
The general way of defining a function is
function function_name (arg1, arg2, arg3, )
{
statement list
}
To return a value from a function, you need to
make a call to return expr inside your function.
This stops execution of the function and returns
expr as the functions value.

Copyright IBM Corporation 2012
User-Defined Functions
The following example function accepts one
argument, $x, and returns its square:
function square ($x){
return $x*$x;}
After defining this function, it can be used as
an expression wherever you desire.
For example:
print 'The square of 5 is ' . square(5);
Copyright IBM Corporation 2012
Function Scope
Every function has its own set of variables.
Any variables used outside the functions
definition are not accessible from within the
function by default.
When a function starts, its function parameters
are defined.
When you use new variables inside a function,
they are defined within the function only and
dont hang around after the function call ends.
Copyright IBM Corporation 2012
Function Scope
In the following example, the variable $var is
not changed by the function call:
function func ()
{
$var = 2;
}
$var = 1;
func();
print $var;
Copyright IBM Corporation 2012
Function Scope
When the function func is called, the variable
$var, which is assigned 2, is only in the scope
of the function and thus does not change $var
outside the function.
The code snippet prints out 1.
Now what if you actually do want to access
and/or change $var on the outside?
you can use the built-in $GLOBALS[] array to
access variables in the global scope of the
script.
Copyright IBM Corporation 2012
Function Scope
Rewrite the previous script the following way:
function func ()
{
$GLOBALS["var"] = 2;
}
$var = 1;
func();
print $var;
It prints the value 2.
Copyright IBM Corporation 2012
Returning Values By Value
The return statement returns values by value,
which means that a copy of the value is created
and is returned to the caller of the function.
For example:
function get_global_variable_value($name){
return $GLOBALS[$name]; }
$num = 10;
$value = get_global_variable_value("num");
print $value;
Copyright IBM Corporation 2012
Returning Values By Value
This code prints the number 10. However,
making changes to $value before the print
statement only affects $value and not the
global variable $num.
This is because its value was returned by the
get_global_variable_value() by value and not
by reference.

Copyright IBM Corporation 2012
Declaring Function Parameters
you can pass an arbitrary amount of arguments
to a function.
There are two different ways of passing these
arguments.
The first is the most common, which is called
passing by value, and the second is called
passing by reference.
Which kind of argument passing you would
like is specified in the function definition itself
and not during the function call.
Copyright IBM Corporation 2012
By-Value Parameters
The argument can be any valid expression, the
expression is evaluated, and its value is
assigned to the corresponding variable in the
function.
For example, here, $x is assigned the value 8
and $y is assigned the value of $c:
function pow($x, $y)
{
...
}
pow(2*4, $c);
Copyright IBM Corporation 2012
By-Reference Parameters
Passing by-reference requires the argument to
be a variable.
Instead of the variables value being passed,
the corresponding variable in the function
directly refers to the passed variable whenever
used.
Thus, if you change it inside the function, it
affects the sent variable in the outer scope as
well
Copyright IBM Corporation 2012
By-Reference Parameters

Example
function square(&$n)
{
$n = $n*$n;
}
$number = 4;
square($number);
print $number;

Copyright IBM Corporation 2012
By-Reference Parameters
The & sign that proceeds $n in the function
parameters tells PHP to pass it by-reference,
and the result of the function call is $number
squared.
thus, this code would print 16.
Copyright IBM Corporation 2012
Default Parameters
Default parameters enable you to specify a
default value for function parameters that
arent passed to the function during the
function call.
The default values you specify must be a
constant value, such as a scalar, array with
scalar values, or constant.
Copyright IBM Corporation 2012
Default Parameters
The following is an example for using default
parameters:
function increment(&$num, $increment = 1)
{
$num += $increment;
}
$num = 4;
increment($num);
increment($num, 3);
Copyright IBM Corporation 2012
Default Parameters
This code results in $num being incremented to
8.
First, it is incremented by 1 by the first call to
increment, where the default increment size of
1 is used, and second, it is incremented by 3,
altogether by 4.
Copyright IBM Corporation 2012
Static Variables
Like C, PHP supports declaring local function
variables as static.
These kind of variables remain in tact in
between function calls, but are still only
accessible from within the function they are
declared.
Static variables can be initialized,and this
initialization only takes place the first time the
static declaration is reached.
Copyright IBM Corporation 2012
Static Variables
Heres an example for the use of static that
runs initialization code the
first time (and only the first time) the
function is run:
function do_something()
{
static first_time = true;
if (first_time) {
// Execute this code only the first time the function is called
...
}
// Execute the function's main logic every time the function iscalled
...
Copyright IBM Corporation 2012
The Include Function
The include function takes a file name and
simply inserts that file's contents into the script
that calls used the include function.
This means that you can type up a common
header or menu file that you want all your web
pages to include.
When you add a new page to your site, instead
of having to update the links on several web
pages, you can simply change the Menu file.
Copyright IBM Corporation 2012
An Include Example
A common practice for naming files that are to
be included is to use the ".php" extension.
Since we want to create a common menu let's
save it as "menu.php".
menu.php Code:
<html>
<body>
<ahref="http://www.example.com/index.php">Home</a>
<ahref="http://www.example.com/about.php">About Us</a>
<ahref="http://www.example.com/links.php">Links</a>
<ahref="http://www.example.com/contact.php">Contact Us</a> <br />
Copyright IBM Corporation 2012
An Include Example
Here we will take advantage of the include
function to add our common menu.
index.php Code:
<?php include("menu.php"); ?>
<p>This is my home page that uses a common
menu to save me time when I add
new pages to my website!</p>
</body>
</html>
Copyright IBM Corporation 2012
PHP Require Function
When you include a file with the include
function and PHP cannot find it you will see an
error message like the following:
PHP Code:
<?php
include("noFileExistsHere.php");
echo "Hello World!";
?>
Display:
Warning: main(noFileExistsHere.php): failed to open stream: No such file or
directory in /home/websiteName/FolderName/tizagScript.php on line 2
Warning: main(): Failed opening 'noFileExistsHere.php' for inclusion
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/websiteName/FolderName/tizagScript.php on line 2 Hello World!
Copyright IBM Corporation 2012
PHP Require Function
PHP Code:
<?php
require("noFileExistsHere.php");
echo "Hello World!";
?>
Display:
Warning: main(noFileExistsHere.php): failed to open stream: No such file
or directory in /home/websiteName/FolderName/tizagScript.php on
line 2 Fatal error: main(): Failed opening required
'noFileExistsHere.php'
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/websiteName/FolderName/tizagScript.php on line 2
Copyright IBM Corporation 2012
PHP Require Function
The echo statement was not executed because
our script execution died after the require
function returned a fatal error.
We recommend that you use require instead of
include because your scripts should not be
executing if necessary files are missing or
misnamed.
Copyright IBM Corporation 2012
Arrays
Arrays are collections of related values, such as
the data submitted from a form, the names of
students in a class, or the populations of a list
of cities.
An array is a container that holds multiple
values, each distinct from the rest.
An array is made up of elements. Each element
has a key and a value.

Copyright IBM Corporation 2012
Arrays
An array holding information about the colors
of vegetables has vegetable names for keys and
colors for values, shown below

Copyright IBM Corporation 2012
Arrays
An array can only have one element with a
given key.
In the vegetable color array, there can't be
another element with the key corn even if its
value is blue.
However, the same value can appear many
times in one array.
You can have orange carrots, orange
tangerines, and orange oranges.
Copyright IBM Corporation 2012
Arrays
Any string or number value can be an array
element key such as corn, 4, -36, or Salt Baked
Squid.
Arrays and other non-scalar[1] values can't be
keys, but they can be element values
An element value can be a string, a number,
true, or false; it can also be another array.
Copyright IBM Corporation 2012
Creating an Array
To create an array, assign a value to a
particular array key. Array keys are denoted
with square brackets,
// An array called $vegetables with string keys
$vegetables['corn'] = 'yellow';
$vegetables['beet'] = 'red';
$vegetables['carrot'] = 'orange';

Copyright IBM Corporation 2012
Creating an Array
You can also create an array using the array( )
language construct.
Creating arrays with array( )
$vegetables = array('corn' => 'yellow',
'beet' => 'red', 'carrot' => 'orange');
With array( ), you specify a comma-delimited
list of key/value pairs.
The key and the value are separated by =>.

Copyright IBM Corporation 2012
Creating an Array
The array( ) syntax is more concise when you
are adding more than one element to an array at
a time.
The square bracket syntax is better when you
are adding elements one by one.
Copyright IBM Corporation 2012
Creating a Numeric Array
PHP provides some shortcuts for working with
arrays that have only numbers as keys.
If you create an array with array() by
specifying only a list of values instead of
key/value pairs, the PHP interpreter
automatically assigns a numeric key to each
value.
The keys start at 0 and increase by 1 for each
element. below example uses this technique to
create the $dinner array.
Copyright IBM Corporation 2012
Creating a Numeric Array
Example :Creating numeric arrays with array( )
$dinner = array('Sweet Corn and Asparagus',
'Lemon Chicken','Braised Bamboo Fungus');
print "I want $dinner[0] and $dinner[1].";
Example prints:
I want Sweet Corn and Asparagus and Lemon
Chicken.
Copyright IBM Corporation 2012
Creating a Numeric Array
Internally, the PHP interpreter treats arrays
with numeric keys and arrays with string keys
(and arrays with a mix of numeric and string
keys) identically.
Because of the resemblance to features in other
programming languages,programmers often
refer to arrays with only numeric keys as
"numeric," "indexed," or "ordered" arrays, and
to string-keyed arrays as "associative" arrays.

Copyright IBM Corporation 2012
Finding the Size of an Array
The count( ) function tells you the number of
elements in an array.
Example. Finding the size of an array
$dinner = array('Sweet Corn and Asparagus',
'Lemon Chicken','Braised Bamboo Fungus');
$dishes = count($dinner);
print "There are $dishes things for dinner.";
Example prints:
There are 3 things for dinner.
Copyright IBM Corporation 2012
Looping Through Arrays
One of the most common things to do with an
array is to consider each element in the array
individually and process it somehow.
This may involve incorporating it into a row of
an HTML table or adding its value to a running
total.
The easiest way to iterate through each element
of an array is with foreach( ).
The foreach( ) construct lets you run a code
block once for each element in an array.
Copyright IBM Corporation 2012
Looping Through Arrays
Example uses foreach( ) to print an HTML
table containing each element in an array.
$meal = array('breakfast' => 'Walnut Bun',
'lunch' => 'Cashew Nuts and White Mushrooms','snack' =>
'Dried Mulberries', 'dinner' => 'Eggplant with Chili Sauce');
print "<table>\n";
foreach ($meal as $key => $value) {
print "<tr><td>$key</td><td>$value</td></tr>\n";
}
print '</table>';
Copyright IBM Corporation 2012
Looping Through Arrays
Example prints:
<table>
<tr><td>breakfast</td><td>Walnut
Bun</td></tr>
<tr><td>lunch</td><td>Cashew Nuts and White
Mushrooms</td></tr>
<tr><td>snack</td><td>DriedMulberries</td></
tr>
<tr><td>dinner</td><td>Eggplant with Chili
Sauce</td></tr> </table>
Copyright IBM Corporation 2012
Looping Through Arrays
For each element in $meal, foreach( ) copies
the key of the element into $key and the value
into $value.
Then, it runs the code inside the curly braces.
In Example , that code prints $key and $value
with some HTML to make a table row.
You can use whatever variable names you want
for the key and value inside the code block. If
the variable names were in use before the
foreach( ), though, they're overwritten with
values from the array.
Copyright IBM Corporation 2012
Modifying Arrays
You can operate on individual array elements
just like regular scalar variables, using
arithmetic, logical, and other operators.
Example . Operating on array elements
$dishes['Beef Chow Foon'] = 12;
$dishes['Beef Chow Foon']++;
$dishes['Roast Duck'] = 3;
$dishes['total'] = $dishes['Beef Chow Foon'] + $dishes['Roast Duck'];
if ($dishes['total']> 15) {
print "You ate a lot: ";}
print 'You ate ' . $dishes['Beef Chow Foon'] . ' dishes of Beef Chow Foon.';
Example prints:
You ate a lot: You ate 13 dishes of Beef Chow Foon.
Copyright IBM Corporation 2012
Converting an Array to String
When you want to print all of the values in an
array at once, the quickest way is to use the
implode( ) function.
It makes a string by combining all the values
in an array and separating them with a string
delimiter. Example prints a comma separated
list of dim sum choices.
Copyright IBM Corporation 2012
Converting an Array to String
$dimsum = array('Chicken Bun','Stuffed Duck Web','Turnip Cake');
$menu = implode(', ', $dimsum);
print $menu;
Example prints:
Chicken Bun, Stuffed Duck Web, Turnip Cake
To implode an array with no delimiter, use the empty string as the first
argument to implode( ):
$letters = array('A','B','C','D');
print implode(' ',$letters);
This prints:
ABCD
Copyright IBM Corporation 2012
Converting an String to Array
The counterpart to implode( ) is called
explode( ). It breaks a string apart into an array.
The delimiter argument to explode( ) is the
string it should look for to separate array
elements. Example demonstrates explode( ).
$fish = 'Bass, Carp, Pike, Flounder';
$fish_list = explode(', ', $fish);
print "The second fish is $fish_list[1]";
Example prints:
The second fish is Carp
Copyright IBM Corporation 2012
Sorting Arrays
There are several ways to sort arrays. Which
function to use depends on how you want to
sort your array and what kind of array it is.
The sort( ) function sorts an array by its
element values.
It should only be used on numeric arrays,
because it resets the keys of the array when it
sorts.

Copyright IBM Corporation 2012
Sorting Arrays
Example
$dinner = array('Sweet Corn and Asparagus',
'Lemon Chicken','Braised Bamboo Fungus');
print "Before Sorting:\n";
foreach ($dinner as $key => $value) {
print " \$dinner: $key $value\n";}
sort($dinner);
print "After Sorting:\n";
foreach ($dinner as $key => $value) {
print " \$dinner: $key $value\n";}
Copyright IBM Corporation 2012
Sorting Arrays
Before Sorting:
$dinner: 0 Sweet Corn and Asparagus
$dinner: 1 Lemon Chicken
$dinner: 2 Braised Bamboo Fungus

After Sorting:
$dinner: 0 Braised Bamboo Fungus
$dinner: 1 Lemon Chicken
$dinner: 2 Sweet Corn and Asparagus
Copyright IBM Corporation 2012
Sorting Arrays
While sort( ) and asort( ) sort arrays by element
value, you can also sort arrays by key with
ksort( ).
This keeps key/value pairs together, but orders
them by key.
Example shows $meal sorted with ksort( ).
Copyright IBM Corporation 2012
Sorting Arrays
$meal = array('breakfast' => 'Walnut Bun','lunch' => 'Cashew
Nuts andWhiteMushrooms', 'snack' => 'Dried Mulberries',
'dinner' => 'Eggplant with Chili Sauce');
print "Before Sorting:\n";
foreach ($meal as $key => $value) {
print " \$meal: $key $value\n";}
ksort($meal);
print "After Sorting:\n";
foreach ($meal as $key => $value) {
print " \$meal: $key $value\n";
}
Copyright IBM Corporation 2012
Sorting Arrays
Example prints:
Before Sorting:
$meal: breakfast Walnut Bun
$meal: lunch Cashew Nuts and White Mushrooms
$meal: snack Dried Mulberries
$meal: dinner Eggplant with Chili Sauce
After Sorting:
$meal: breakfast Walnut Bun
$meal: dinner Eggplant with Chili Sauce
$meal: lunch Cashew Nuts and White Mushrooms
$meal: snack Dried Mulberries
Copyright IBM Corporation 2012
Sorting Arrays
The array is reordered so the keys are now in
ascending alphabetical order.
Each element is unchanged, so the value that
went with each key before the sorting is the
same as each key value after the sorting.
If you sort a numeric array with ksort( ), then
the elements are ordered so the keys are in
ascending numeric order.
This is the same order you start out with when
you create a numeric array using array( ) or [ ].
Copyright IBM Corporation 2012
Using Multidimensional Arrays
The value of an array element can be another
array.
This is useful when you want to store data that
has a more complicated structure than just a
key and a single value.
A standard key/value pair is fine for matching
up a meal name with a single dish but what
about when each meal consists of more than
one dish? Then, element values should be
arrays, not strings.
Copyright IBM Corporation 2012
Using Multidimensional Arrays
$meals = array('breakfast' => array('Walnut
Bun','Coffee'),'lunch' => array('Cashew Nuts',
'White Mushrooms'),'snack' => array('Dried
Mulberries','Salted Sesame Crab'));
$lunches=>array(
array('Chicken','Eggplant','Rice'),array('Beef',
'Scallions','Noodles'),array('Eggplant','Tofu'))
;
$flavors = array('Japanese' => array('hot' =>
'wasabi','salty' => 'soy sauce'),'Chinese' =>
array('hot' => 'mustard','pepper-salty' =>
'prickly ash'));
Copyright IBM Corporation 2012
Accessing multidimensional array
Accessing multidimensional array elements
print $meals['lunch'][1]; // White Mushrooms
print $meals['snack'][0]; // Dried Mulberries
print $lunches[0][0]; // Chicken
print $lunches[2][1]; // Tofu
print $flavors['Japanese']['salty'] // soy sauce
print $flavors['Chinese']['hot']; // mustard
Copyright IBM Corporation 2012
Iterating multidimensional array
$flavors = array('Japanese' => array('hot' => 'wasabi','salty'
=> 'soy sauce'),'Chinese' => array('hot' => 'mustard','pepper-
salty' => 'prickly ash'));
// $culture is the key and $culture_flavors is the value (an
array)
foreach ($flavors as $culture => $culture_flavors) {
// $flavor is the key and $example is the value
foreach ($culture_flavors as $flavor => $example) {
print "A $culture $flavor flavor is $example.\n";
}
}
Copyright IBM Corporation 2012
Iterating multidimensional array
Example prints:
A Japanese hot flavor is wasabi.
A Japanese salty flavor is soy sauce.
A Chinese hot flavor is mustard.
A Chinese pepper-salty flavor is prickly ash.

You might also like