Ch7 - Osp With PHP
Ch7 - Osp With PHP
7.
OPEN
SOURCE
PROGRAMMING
WITH
PHP
[Link]
-‐
1
INTRODUCTION
Static
vs.
Dynamic
websites
A
static
website
is
created
using
HTML
pages
which
have
been
written
in
a
fixed
way
to
instruct
the
browser
how
to
render
the
page.
(What
You
See
Is
What
You
Get).
Static
websites
are
used
to
display
fixed
information
that
does
not
need
to
be
updated
on
a
regular
basis.
As
the
Web
evolved,
sites
became
more
complex
and
were
expected
to
display
dynamic
information
that
could
not
have
been
“hard
coded”
in
HTML.
Dynamic
websites
The
solution
was
to
generate
the
HTML
“on-‐the-‐fly”
based
on
parameters
and
specifications.
For
example,
if
a
user
asks
to
see
search
results,
a
unique
page
would
be
generated
specifically
for
him.
Since
there
is
no
way
of
knowing
every
possible
search
result
for
every
possible
keyword,
the
final
page
is
being
assembled
using
a
server-‐side
script.
The
server-‐side
script
constructs
the
page
and
then
it
is
being
sent
back
to
the
client.
This
means
that
the
page
[Link]
will
look
different
each
time
based
on
the
given
specifications.
Every
client
makes
a
request
for
a
page.
The
server
checks
what
the
client
has
asked
for
and
based
on
that,
it
constructs
a
page
for
him
on
an
existing
template.
The
template
is
a
page,
which
contains
HTML
code
and
server-‐
side
code
that
will
end
up
as
HTML
code
as
well,
but
a
different
HTML
each
time.
Three
Tier
Web
Applications
Benefits
Of
Dynamic
Content
• The
ability
to
customize
pages
for
any
given
user.
• Greater
ease
of
modification
and
update.
• Extended
functionality
(login,
transactions,
communication
etc.).
• Automating
the
site
and
allowing
it
to
support
itself.
Fewer
pages
to
be
created
manually.
Before
you
proceed
it
is
important
to
make
sure
that
you
have
proper
environment
setup
on
your
machine
to
develop
your
web
programs
using
PHP.
Type
the
following
address
into
your
browser's
address
box.
[Link]
-‐
2
If
this
displays
a
page
showing
your
PHP
installation
related
information
then
it
means
you
have
PHP
and
Webserver
installed
properly.
Otherwise
you
have
to
follow
given
procedure
to
install
PHP
on
your
computer.
Server-‐Side
Scripting
In
order
to
generate
dynamic
pages
we
use
a
server-‐side
scripting
language.
There
are
different
types
of
server-‐
side
scripting
languages
such
as
PHP,
ASP,
[Link],
ColdFusion,
JavaServer
Pages,
Perl
and
others.
Each
scripting
languages
is
being
interpreted
by
an
application,
just
as
Flash
is
used
to
make
sense
of
ActionScript
and
have
the
code
do
things.
The
application
which
interprets
the
server-‐side
script
is
installed
on
the
sever
just
like
any
other
application.
Server-‐side
scripting
languages
are
also
operating
systems
dependent.
PHP
for
example,
is
being
interpreted
by
an
application
called
Apache.
Each
server-‐side
scripting
language
supports
basic
programming
concepts
such
as
variables,
arrays,
functions,
loops,
conditional
statement
and
others.
They
also
contain
more
specific
elements
such
as
special
objects,
commands
used
to
communicate
with
the
server
and
a
database
and
much
more.
Server-‐Side
Scripting
&
Databases
When
there
is
a
need
to
store
and
retrieve
information
(members,
items
in
stock
etc.)
a
database
will
be
used
to
contain
the
data.
Sever-‐side
script
can
communicate
to
a
database
using
a
structured
query
language(SQL)
which
manipulates
the
database
(add,
remove,
update,
delete
etc.)
What
is
PHP?
PHP
started
out
as
a
small
open
source
project
that
evolved
as
more
and
more
people
found
out
how
useful
it
was.
Rasmus
Lerdorf
unleashed
the
first
version
of
PHP
way
back
in
1994.
• PHP
performs
system
functions,
i.e.
from
files
on
a
system
it
can
create,
open,
read,
write,
and
close
them.
• PHP
can
handle
forms,
i.e.
gather
data
from
files,
save
data
to
a
file,
thru
email
you
can
send
data,
return
data
to
the
user.
• You
add,
delete,
and
modify
elements
within
your
database
thru
PHP.
• Access
cookies
variables
and
set
cookies.
• Using
PHP,
you
can
restrict
users
to
access
some
pages
of
your
website.
• It
can
encrypt
data.
Before
starting
this
tutorial
it
is
important
that
you
have
a
basic
understanding
and
experience
in
the
following:
<?PHP
…
?>
[Link]
-‐
4
Syntax,
Variables
&
Strings
Basic
PHP
Syntax
You
cannot
view
the
PHP
source
code
by
selecting
"View
source"
in
the
browser
–
you
will
only
see
the
output
from
the
PHP
file,
which
is
plain
HTML.
This
is
because
the
scripts
are
executed
on
the
server
before
the
result
is
sent
back
to
the
browser.
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
?>.
However,
for
maximum
compatibility,
recommended
is
that
you
use
the
standard
form
(<?php)
rather
than
the
shorthand
form.
<?php
…
?>
A
PHP
file
normally
contains
HTML
tags,
just
like
an
HTML
file,
and
some
PHP
scripting
code.
<html>
<body>
<?php
echo
"Hello
World";
?>
</body>
</html>
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".
Comments
In
PHP
In
PHP,
we
use
//
to
make
a
single-‐line
comment
or
/*
and
*/
to
make
a
large
comment
block.
<html>
<body>
<?php
//This
is
a
comment
/*
This
is
a
comment
block.
*/
?>
</body>
</html>
PHP
Variables
Variables
are
used
for
storing
a
value,
like
text
strings,
numbers
or
arrays.
When
a
variable
is
set
it
can
be
used
over
and
over
again
in
your
script.
All
variables
in
PHP
start
with
a
$
sign
symbol.
The
correct
way
of
setting
a
variable
in
PHP:
$var_name
=
value;
New
PHP
programmers
often
forget
the
$
sign
at
the
beginning
of
the
variable.
In
that
case
it
will
not
work.
Let's
try
creating
a
variable
with
a
string,
and
a
variable
with
a
number:
<?php
$txt
=
"Hello
World!";
$number
=
16;
?>
[Link]
-‐
5
PHP
is
a
Loosely
Typed
Language
In
PHP
a
variable
does
not
need
to
be
declared
before
being
set.
In
the
previous
example,
you
see
that
you
do
not
have
to
tell
PHP
which
data
type
the
variable
is.
PHP
automatically
converts
the
variable
to
the
correct
data
type,
depending
on
how
they
are
set.
In
a
strongly
typed
programming
language,
you
have
to
declare
(define)
the
type
and
name
of
the
variable
before
using
it
(Like
in
C,
C++
Programming.).
In
PHP
the
variable
is
declared
automatically
when
you
use
it.
Variable
Naming
Rules
• A
variable
name
must
start
with
a
letter
or
an
underscore
"_".
• A
variable
name
can
only
contain
alpha-‐numeric
characters
and
underscores
(a-‐Z,
0-‐9,
and
_
).
• A
variable
name
should
not
contain
spaces.
If
a
variable
name
is
more
than
one
word,
it
should
be
separated
with
underscore
($my_string),
or
with
capitalization
($myString).
The scope of a variable is the portion of the script in which the variable can be referenced.
• local
• global
• static
• parameter
Local
Scope
A
variable
declared
within
a
PHP
function
is
local
and
can
only
be
accessed
within
that
function.
(the
variable
has
local
scope):
<?php
$a
=
5;
//
global
scope
function
myTest()
{
echo
$a;
//
local
scope
}
myTest();
?>
The
script
above
will
not
produce
any
output
because
the
echo
statement
refers
to
the
local
scope
variable
$a,
which
has
not
been
assigned
a
value
within
this
scope.
You
can
have
local
variables
with
the
same
name
in
different
functions,
because
local
variables
are
only
recognized
by
the
function
in
which
they
are
declared.
Local
variables
are
deleted
as
soon
as
the
function
is
completed.
[Link]
-‐
6
Global
Scope
Global
scope
refers
to
any
variable
that
is
defined
outside
of
any
function.
Global
variables
can
be
accessed
from
any
part
of
the
script
that
is
not
inside
a
function.
To
access
a
global
variable
from
within
a
function,
use
the
global
keyword:
<?php
$a
=
5;
$b
=
10;
function
myTest()
{
global
$a,
$b;
$b
=
$a
+
$b;
}
myTest();
echo
$b;
?>
PHP
also
stores
all
global
variables
in
an
array
called
$GLOBALS[index].
Its
index
is
the
name
of
the
variable.
This
array
is
also
accessible
from
within
functions
and
can
be
used
to
update
global
variables
directly.
The
example
above
can
be
rewritten
as
this:
<?php
$a
=
5;
$b
=
10;
function
myTest()
{
$GLOBALS['b']
=
$GLOBALS['a']
+
$GLOBALS['b'];
}
myTest();
echo
$b;
?>
Static
Scope
When
a
function
is
completed,
all
of
its
variables
are
normally
deleted.
However,
sometimes
you
want
a
local
variable
to
not
be
deleted.
To do this, use the static keyword when you first declare the variable:
static $rememberMe;
[Link]
-‐
7
Then,
each
time
the
function
is
called,
that
variable
will
still
have
the
information
it
contained
from
the
last
time
the
function
was
called.
Parameters
A
parameter
is
a
local
variable
whose
value
is
passed
to
the
function
by
the
calling
code.
Parameters
are
declared
in
a
parameter
list
as
part
of
the
function
declaration:
function
myTest($para1,$para2,...)
{
//
function
code
}
Thus
far
we
have
created
strings
using
double-‐quotes,
but
it
is
just
as
correct
to
create
a
string
using
single-‐
quotes,
otherwise
known
as
apostrophes.
PHP
Code:
$my_string
=
'KCC
-‐
Unlock
your
potential!';
echo
'KCC
-‐
Unlock
your
potential!';
echo
$my_string;
If
you
want
to
use
a
single-‐quote
within
the
string
you
have
to
escape
the
single-‐quote
with
a
backslash
\
.
Like
this:
\'
!
PHP
Code:
echo
'It\'s
Neat!';
PHP
-‐
string
creation
double-‐quotes
[Link]
-‐
8
We
have
used
double-‐quotes
and
will
continue
to
use
them
as
the
primary
method
for
forming
strings.
Double-‐
quotes
allow
for
many
special
escaped
characters
to
be
used
that
you
cannot
do
with
a
single-‐quote
string.
Once
again,
a
backslash
is
used
to
escape
a
character.
PHP
Code:
$newline
=
"A
newline
is
\n";
$return
=
"A
carriage
return
is
\r";
$tab
=
"A
tab
is
\t";
$dollar
=
"A
dollar
sign
is
\$";
$doublequote
=
"A
double-‐quote
is
\"";
Note:
If
you
try
to
escape
a
character
that
doesn't
need
to
be,
such
as
an
apostrophe,
then
the
backslash
will
show
up
when
you
output
the
string.
These
escaped
characters
are
not
very
useful
for
outputting
to
a
web
page
because
HTML
ignore
extra
white
space.
A
tab,
newline,
and
carriage
return
are
all
examples
of
extra
(ignorable)
white
space.
However,
when
writing
to
a
file
that
may
be
read
by
human
eyes
these
escaped
characters
are
a
valuable
tool!
The
two
methods
above
are
the
traditional
way
to
create
strings
in
most
programming
languages.
PHP
introduces
a
more
robust
string
creation
tool
called
heredoc
that
lets
the
programmer
create
multi-‐line
strings
without
using
quotations.
However,
creating
a
string
using
heredoc
is
more
difficult
and
can
lead
to
problems
if
you
do
not
properly
code
your
string!
Here's
how
to
do
it:
PHP
Code:
$my_string
=
<<<TEST
'KCC
-‐
Unlock
your
potential
TEST;
echo
$my_string;
There are a few very important things to remember when using heredoc.
• Use
<<<
and
some
identifier
that
you
choose
to
begin
the
heredoc.
In
this
example
we
chose
TEST
as
our
identifier.
• Repeat
the
identifier
followed
by
a
semicolon
to
end
the
heredoc
string
creation.
In
this
example
that
was
TEST;
• The
closing
sequence
TEST;
must
occur
on
a
line
by
itself
and
cannot
be
indented!
Another
thing
to
note
is
that
when
you
output
this
multi-‐line
string
to
a
web
page,
it
will
not
span
multiple
lines
because
we
did
not
have
any
<br
/>
tags
contained
inside
our
string!
Here
is
the
output
made
from
the
code
above.
Output:
'KCC
-‐
Unlock
your
potential
The
Concatenation
Operator
There
is
only
one
string
operator
in
PHP.
The
concatenation
operator
(.)
is
used
to
put
two
string
values
[Link]
concatenate
two
variables
together,
use
the
dot
(.)
operator:
[Link]
-‐
9
<?php
$txt1="Hello
World";
$txt2="1234";
echo
$txt1
.
"
"
.
$txt2;
?>
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.
The
output
of
the
code
will
be:
Hello
World
1234
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!");
?>
The
output
of
the
code
above
will
be:
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)
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");
?>
The
output
of
the
code
above
will
be:
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.
Operators
In
all
programming
languages,
operators
are
used
to
manipulate
or
perform
operations
on
variables
and
values.
We
have
already
seen
the
string
concatenation
operator
"."
and
the
assignment
operator
"="
in
pretty
much
every
PHP
example
so
far.
There
are
many
operators
used
in
PHP,
so
we
have
separated
them
into
the
following
categories
to
make
it
easier
to
learn
them
all.
• Assignment
Operators
• Arithmetic
Operators
• Comparison
Operators
The
assignment
operator
=
is
used
to
assign
values
to
variables
in
PHP.
The
arithmetic
operator
+
is
used
to
add
values
together.
Arithmetic
Operators
Assignment Operators
The
basic
assignment
operator
in
PHP
is
"=".
It
means
that
the
left
operand
gets
set
to
the
value
of
the
expression
on
the
right.
That
is,
the
value
of
"$x
=
5"
is
5.
Incrementing/Decrementing Operators
x <= y Less than or equal to True if x is less than or equal to y 5<=8 returns true
Logical Operators
Array Operators
Conditional Statements
• if
statement
-‐
use
this
statement
to
execute
some
code
only
if
a
specified
condition
is
true
• if...else
statement
-‐
use
this
statement
to
execute
some
code
if
a
condition
is
true
and
another
code
if
the
condition
is
false
• if...elseif....else
statement
-‐
use
this
statement
to
select
one
of
several
blocks
of
code
to
be
executed
• switch
statement
-‐
use
this
statement
to
select
one
of
many
blocks
of
code
to
be
executed
The
if
Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if
(condition)
code
to
be
executed
if
condition
is
true;
The following example will output "Have a nice weekend!" if the current day is Friday:
<html>
<body>
<?php
$d=date("D");
if
($d=="Fri")
echo
"Have
a
nice
weekend!";
?>
</body>
</html>
Note that there is no ‘else’ in this syntax. The code is executed only if the specified condition is true.
The
if...else
Statement
Use the if... else statement to execute some code if a condition is true and another code if a condition is false.
Example
The
following
example
will
output
"Have
a
nice
weekend!"
if
the
current
day
is
Friday,
otherwise
it
will
output
"Have
a
nice
day!"
<html>
<body>
<?php
$d=date("D");
if
($d=="Fri")
{
echo
"Have
a
nice
weekend!";
}
else
{
echo
"Have
a
nice
day!";
}
?>
</body>
</html>
The
if...
elseif...
else
Statement
Use the if... elseif… else statement to select one of several blocks of code to be executed.
Syntax
if
(condition)
{
code
to
be
executed
if
condition
is
true;
}
elseif
(condition)
{
code
to
be
executed
if
condition
is
true;
}
else
{
Example
The
following
example
will
output
"Have
a
nice
weekend!"
if
the
current
day
is
Friday,
and
"Have
a
nice
Sunday!"
if
the
current
day
is
Sunday.
Otherwise
it
will
output
"Have
a
nice
day!":
<html>
<body>
<?php
$d=date("D");
if
($d=="Fri")
{
echo
"Have
a
nice
weekend!";
}
elseif
($d=="Sun")
{
echo
"Have
a
nice
Sunday!";
}
else
{
echo
"Have
a
nice
day!";
}
?>
</body>
</html>
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch
(n)
{
case
label1:
code
to
be
executed
if
n=label1;
break;
case
label2:
code
to
be
executed
if
n=label2;
break;
default:
code
to
be
executed
if
n
is
different
from
both
label1
and
label2;
}
Example
<html>
<body>
<?php
$x=1;
switch
($x)
{
case
1:
echo
"Number
1";
break;
case
2:
echo
"Number
2";
break;
case
3:
echo
"Number
3";
break;
default:
echo
"No
number
between
1
and
3";
}
?>
</body>
</html>
Loops execute a block of code a specified number of times, or while a specified condition is true.
PHP
Loops
Often
when
you
write
code,
you
want
the
same
block
of
code
to
run
over
and
over
again
in
a
row.
Instead
of
adding
several
almost
equal
lines
in
a
script
we
can
use
loops
to
perform
a
task
like
this.
• while
-‐
loops
through
a
block
of
code
while
a
specified
condition
is
true
• do...while
-‐
loops
through
a
block
of
code
once,
and
then
repeats
the
loop
as
long
as
a
specified
condition
is
true
• for
-‐
loops
through
a
block
of
code
a
specified
number
of
times
• foreach
-‐
loops
through
a
block
of
code
for
each
element
in
an
array
The while loop executes a block of code while a condition is true.
Syntax
while
(condition)
{
code
to
be
executed;
}
Example
Then,
the
while
loop
will
continue
to
run
as
long
as
i
is
less
than,
or
equal
to
5.
i
will
increase
by
1
each
time
the
loop
runs:
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo
"The
number
is
"
.
$i
.
"<br>";
$i++;
}
?>
</body>
</html>
Output:
The
do...while
statement
will
always
execute
the
block
of
code
once,
it
will
then
check
the
condition,
and
repeat
the
loop
while
the
condition
is
true.
Syntax
do
{
Example
Then,
it
starts
the
do...while
loop.
The
loop
will
increment
the
variable
i
with
1,
and
then
write
some
output.
Then
the
condition
is
checked
(is
i
less
than,
or
equal
to
5),
and
the
loop
will
continue
to
run
as
long
as
i
is
less
than,
or
equal
to
5:
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo
"The
number
is
"
.
$i
.
"<br>";
}
while
($i<=5);
?>
</body>
</html>
Output:
The for loop is used when you know in advance how many times the script should run.
Syntax
for
(init;
condition;
increment)
{
code
to
be
executed;
}
Parameters:
• init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
Note:
The
init
and
increment
parameters
above
can
be
empty
or
have
multiple
expressions
(separated
by
commas).
Example
The
example
below
defines
a
loop
that
starts
with
i=1.
The
loop
will
continue
to
run
as
long
as
the
variable
i
is
less
than,
or
equal
to
5.
The
variable
i
will
increase
by
1
each
time
the
loop
runs:
<html>
<body>
<?php
for
($i=1;
$i<=5;
$i++)
{
echo
"The
number
is
"
.
$i
.
"<br>";
}
?>
</body>
</html>
Output:
Syntax
foreach
($array
as
$value)
{
code
to
be
executed;
}
For
every
loop
iteration,
the
value
of
the
current
array
element
is
assigned
to
$value
(and
the
array
pointer
is
moved
by
one)
-‐
so
on
the
next
loop
iteration,
you'll
be
looking
at
the
next
array
value.
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$x=array("one","two","three");
foreach
($x
as
$value)
{
echo
$value
.
"<br>";
}
?>
</body>
</html>
Output:
one
two
three
Array
Like arrays in other languages, PHP arrays allow you to store multiple values in a single variable and
operate on them as a set.
A
variable
is
a
storage
area
holding
a
number
or
text.
The
problem
is,
a
variable
will
hold
only
one
value.
An
array
is
a
special
variable,
which
can
store
multiple
values
in
one
single
variable.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1="Saab";
$cars2="Volvo";
$cars3="BMW";
However,
what
if
you
want
to
loop
through
the
cars
and
find
a
specific
one?
And
what
if
you
had
not
3
cars,
but
300?
Each element in the array has its own index so that it can be easily accessed.
• Numeric
array
(Enumerated
Arrays)
-‐
An
array
with
a
numeric
index
• Associative
array
-‐
An
array
where
each
ID
key
is
associated
with
a
value
• Multidimensional
array
-‐
An
array
containing
one
or
more
arrays
Numeric
Arrays
(Enumerated
Arrays)
1. In the following example the index are automatically assigned (the index starts at 0):
$cars=array("Saab","Volvo","BMW","Toyota");
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
Example
In the following example you access the variable values by referring to the array name and index:
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo
$cars[0]
.
"
and
"
.
$cars[1]
.
"
are
Swedish
cars.";
?>
When storing data about specific named values, a numerical array is not always the best way to do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
In this example we use an array to assign ages to the different persons:
Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter']
=
"32";
$ages['Quagmire']
=
"30";
$ages['Joe']
=
"34";
<?php
$ages['Peter']
=
"32";
$ages['Quagmire']
=
"30";
$ages['Joe']
=
"34";
echo
"Peter
is
"
.
$ages['Peter']
.
"
years
old.";
?>
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.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families
=
array
(
"Griffin"=>array
(
[Link]
-‐
23
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
The array above would look like this if written to the output:
Array
(
[Griffin]
=>
Array
(
[0]
=>
Peter
[1]
=>
Lois
[2]
=>
Megan
)
[Quagmire]
=>
Array
(
[0]
=>
Glenn
)
[Brown]
=>
Array
(
[0]
=>
Cleveland
[1]
=>
Loretta
[2]
=>
Junior
)
)
Example 2
echo "Is " . $families['Griffin'][2] . " a part of the Griffin family?";
Code:
This
function
accepts
a
PHP
$data
=
array("hero"
=>
"Holmes",
array
and
returns
a
new
"villain"
=>
"Moriarty");
array
containing
only
its
print_r(array_values($data));
values
(not
its
keys).
Its
?>
counterpart
is
the
array_values($arr)
array_keys()
function.
Output:
Array
Use
this
function
to
retrieve
(
all
the
values
from
an
[0]
=>
Holmes
associative
array.
[1]
=>
Moriarty
)
Code:
This
function
accepts
a
PHP
$data
=
array("hero"
=>
"Holmes",
array
and
returns
a
new
"villain"
=>
"Moriarty");
array
containing
only
its
print_r(array_keys($data));
keys
(not
its
values).
Its
?>
counterpart
is
the
array_keys($arr)
array_values()
function.
Output:
Array
Use
this
function
to
retrieve
(
all
the
keys
from
an
[0]
=>
hero
associative
array.
[1]
=>
villain
)
Code:
$data
=
array("Donald",
"Jim",
"Tom");
array_pop($data);
print_r($data);
This
function
removes
an
?>
array_pop($arr)
element
from
the
end
of
an
array.
Output:
Array
(
[0]
=>
Donald
[1]
=>
Jim
)
Code:
$data
=
array(1,1,4,6,7,4);
This
function
strips
an
array
print_r(array_unique($data));
of
duplicate
values.
?>
Use
this
function
when
you
Output:
array_unique($data)
need
to
remove
non-‐unique
Array
elements
from
an
array—for
(
example,
when
creating
an
[0]
=>
1
array
to
hold
values
for
a
[3]
=>
6
table's
primary
key.
[4]
=>
7
[5]
=>
4
)
This
function
"walks"
Code:
array_walk($arr,
$func)
through
an
array,
applying
a
function
reduceBy10(&$val,
$key)
{
user-‐defined
function
to
$val
-‐=
$val
*
0.1;
every
element.
It
returns
the
}
PHP
Functions
A
function
is
just
a
name
we
give
to
a
block
of
code
that
can
be
executed
whenever
we
need
it.
This
might
not
seem
like
that
big
of
an
idea,
but
believe
me,
when
you
understand
and
use
functions
you
will
be
able
to
save
a
ton
of
time
and
write
code
that
is
much
more
readable!
For
example,
you
might
have
a
company
motto
that
you
have
to
display
at
least
once
on
every
webpage.
If
you
don't,
then
you
get
fired!
Well,
being
the
savvy
PHP
programmer
you
are,
you
think
to
yourself,
"this
sounds
like
a
situation
where
I
might
need
functions."
Tip:
Although
functions
are
often
thought
of
as
an
advanced
topic
for
beginning
programmers
to
learn,
if
you
take
it
slow
and
stick
with
it,
functions
can
be
just
minor
speed
bump
in
your
programming
career.
So
don't
give
up
if
functions
confuse
you
at
first!
To
keep
the
script
from
being
executed
when
the
page
loads,
you
can
put
it
into
a
function.
A
function
will
be
executed
by
a
call
to
the
function.
You
may
call
a
function
from
anywhere
within
a
page.
+
PHP
User
Defined
Functions
Create
a
PHP
Function
• Give
the
function
a
name
that
reflects
what
the
function
does
• The
function
name
can
start
with
a
letter
or
underscore
(not
a
number)
Example
A simple function that writes my name when it is called:
<html>
<body>
<?php
function
writeName()
{
echo
"Kai
Jim
Refsnes";
}
echo
"My
name
is
";
writeName();
?>
</body>
</html>
Output:
To
add
more
functionality
to
a
function,
we
can
add
parameters.
A
parameter
is
just
like
a
variable.
Parameters
are
specified
after
the
function
name,
inside
the
parentheses.
Example 1
The following example will write different first names, but equal last name:
<html>
<body>
<?php
function
writeName($fname)
{
echo
$fname
.
"
Refsnes.<br>";
}
echo
"My
name
is
";
[Link]
-‐
30
writeName("Kai
Jim");
echo
"My
sister's
name
is
";
writeName("Hege");
echo
"My
brother's
name
is
";
writeName("Stale");
?>
</body>
</html>
Output:
Example 2
<html>
<body>
<?php
function
writeName($fname,$punctuation)
{
echo
$fname
.
"
Refsnes"
.
$punctuation
.
"<br>";
}
echo
"My
name
is
";
writeName("Kai
Jim",".");
echo
"My
sister's
name
is
";
writeName("Hege","!");
echo
"My
brother's
name
is
";
writeName("Ståle","?");
?>
</body>
</html>
Output:
Example
<html>
<body>
[Link]
-‐
31
<?php
function
add($x,$y)
{
$total=$x+$y;
return
$total;
}
echo
"1
+
16
=
"
.
add(1,16);
?>
</body>
</html>
Output:
1
+
16
=
17
substr()
This function returns the part of the string as an output.
Syntax
:
substr(<string>,<start>,[<length>]);
Explanation
:
String : It is mandatory parameter. The string from which the part is to be extracted is mentioned here.
Start : The start in the string from which the characters are to be extracted
Length : It is an optional parameter. It specifies the length of the string which is to be extracted.
• Positive
number
–
The
length
to
be
returned
from
the
start
parameter
• Negative
number
–
The
length
to
be
returned
from
the
end
of
the
string
Example
1:
<?php
echo
substr("Hello
world",6);
?>
//Returns
world
Example
2
:
<?php
echo
substr("Hello
world",6,4);
?>
//
Returns
worl
Example
3
:
<?php
echo
substr("Hello
world",
-‐1);
?>
//
Returns
d
Example
4:
<?php
echo
substr("Hello
world",
-‐3,
-‐1);
?>
//
Returns
rl
strlen()
Syntax
:
strlen(<string>);
Explanation:
String : It is mandatory field. The string whose length is to be found out is mentioned here.
Example
1:
<?php
echo
strlen("Hello
world");
?>
//
Returns
11
trim()
This function removes the whitespaces from both start and the end of the string.
Syntax
:
trim(<string>);
[Link]
-‐
33
Explanation
:
String : It is mandatory field. The string of which the whitespaces are to be removed is passed as parameter.
Example
1:
<?php
echo
trim(
"
Hello
World
");
?>
Returns
Hello
World.
If
you
go
view
source
then
you
can
see
that
there
are
no
whitespaces.
ltrim()
This function removes the whitespaces from the left part of the string.
Syntax
:
ltrim(<string>);
Explanation
:
String
:
It
is
mandatory
field.
The
string
of
which
the
whitespaces
are
to
be
removed
from
left
side
is
passed
as
parameter.
Example
1:
<?php
echo
ltrim(
"
Hello
World
");
?>
Returns
Hello
World.
If
you
go
view
source
then
you
can
see
that
there
are
no
whitespaces
on
left
side
but
there
are
spaces
on
right
side.
rtrim()
This
function
removes
the
whitespaces
from
the
right
part
of
the
string.
Syntax
:
rtrim(<string>);
Explanation
:
String
:
It
is
mandatory
field.
The
string
of
which
the
whitespaces
are
to
be
removed
from
right
side
is
passed
as
parameter.
Example
1:
<?php
echo
rtrim(
"
Hello
World
");
?>
Returns
Hello
World.
If
you
go
view
source
then
you
can
see
that
there
are
no
whitespaces
on
right
side
but
there
are
spaces
on
left
side.
strtolower()
Syntax
:
strtolower(<string>);
Explanation
:
String : It is mandatory field. The string which is to be converted to lower case is passed here.
Example 1:
Syntax
:
strtoupper(<string>);
Explanation
:
String : It is mandatory field. The string which is to be converted to upper case is passed here.
Example
1:
<?php
echo
strtoupper("hello
world");
?>
//
Returns
HELLO
WORLD
str_replace()
The
str_replace()
function
replaces
some
characters
with
some
other
characters
in
a
string.
This
function
works
by
the
following
rules:
• If
the
string
to
be
searched
is
an
array,
it
returns
an
array
• If
the
string
to
be
searched
is
an
array,
find
and
replace
is
performed
with
every
array
element
• If
both
find
and
replace
are
arrays,
and
replace
has
fewer
elements
than
find,
an
empty
string
will
be
used
as
replace
• If
find
is
an
array
and
replace
is
a
string,
the
replace
string
will
be
used
for
every
find
value
Syntax
:
str_replace(<search>,<replace>,<string/array>,[<count>]);
Explanation
:
Search : It is mandatory . The string or value to be searched comes here.
Replace : It is mandatory. The string or value to be replaced comes here.
String/Array : It is mandatory. The string or array in which the value is to be found out comes here.
Count : It is optional. It counts the number of replacements to be done.
Example
1:
<?php
echo
str_replace("world","Peter","Hello
world");
?>//
Returns
Hello
Peter
Example
2:
<?php
$arr
=
array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo
"Replacements:
$i";
?>
Output:
Array
(
[0]
=>
blue
[Link]
-‐
35
[1]
=>
pink
[2]
=>
green
[3]
=>
yellow
)
Replacements:
1
strcmp()
Example
1:
<?php
echo
strcmp("Hello
world!","Hello
world!");
?>
//Returns
0
Note:
The
strcmp()
function
is
binary
safe
and
case-‐sensitive.
For
case
insensitive
comparison
you
can
use
strcasecmp(<string1>,<string2>);
function.
It
is
similar
to
strcmp()
function.
explode()
This function breaks the string into array on the basis of delimiter passed.
Syntax:
explode(<delimeter>,<string>,[<limit>]);
Explanation:
Delimeter: It is mandatory field. It specifies where to break the string.
String: It is mandatory. It specifies the string to split.
Limit : It is optional. It specifies the maximum number of array elements to return.
Example
1:
<?php
$str
=
"Hello
world.
It's
a
beautiful
day.";
Delimiter:
It
is
mandatory
field.
It
specifies
what
to
put
between
the
array
elements.
Default
is
“”
(an
empty
string).
Array: It is mandatory field. It specifies the array to join to a string.
Example
1:
<?php
$arr
=
array('Hello','World!','Beautiful','Day!');
echo
implode("
",$arr);
?>
Output:
Hello
World!
Beautiful
Day!
The
fopen()
function
is
used
to
open
files
in
PHP.
The
first
parameter
of
this
function
contains
the
name
of
the
file
to
be
opened
and
the
second
parameter
specifies
in
which
mode
the
file
should
be
opened:
<html>
<body>
<?php
$file=fopen("[Link]","r");
?>
</body>
</html>
The file may be opened in one of the following modes:
Modes
Description
r
Read
only.
Starts
at
the
beginning
of
the
file
r+
Read/Write.
Starts
at
the
beginning
of
the
file
w
Write
only.
Opens
and
clears
the
contents
of
file;
or
creates
a
new
file
if
it
doesn't
exist
w+
Read/Write.
Opens
and
clears
the
contents
of
file;
or
creates
a
new
file
if
it
doesn't
exist
a
Append.
Opens
and
writes
to
the
end
of
the
file
or
creates
a
new
file
if
it
doesn't
exist
a+
Read/Append.
Preserves
file
content
by
writing
to
the
end
of
the
file
x
Write
only.
Creates
a
new
file.
Returns
FALSE
and
an
error
if
file
already
exists
x+
Read/Write.
Creates
a
new
file.
Returns
FALSE
and
an
error
if
file
already
exists
Note: If the fopen() function is unable to open the specified file, it returns 0 (false).
Example
The following example generates a message if the fopen() function is unable to open the specified file:
<html>
<body>
<?php
$file=fopen("[Link]","r")
or
exit("Unable
to
open
file!");
?>
The fclose() function is used to close an open file:
<?php
$file
=
fopen("[Link]","r");
//some
code
to
be
executed
fclose($file);
?>
Check
End-‐of-‐file
The
feof()
function
checks
if
the
"end-‐of-‐file"
(EOF)
has
been
reached.
The
feof()
function
is
useful
for
looping
through
data
of
unknown
length.
Note: You cannot read from files opened in w, a, and x mode!
The fgets() function is used to read a single line from a file.
Note: After a call to this function the file pointer has moved to the next line.
Example
The example below reads a file line by line, until the end of file is reached:
<?php
$file
=
fopen("[Link]",
"r")
or
exit("Unable
to
open
file!");
//Output
a
line
of
the
file
until
the
end
is
reached
while(!feof($file))
{
echo
fgets($file).
"<br>";
}
fclose($file);
?>
The fgetc() function is used to read a single character from a file.
Note: After a call to this function the file pointer moves to the next character.
Example
The example below reads a file character by character, until the end of file is reached:
<?php
$file=fopen("[Link]","r")
or
exit("Unable
to
open
file!");
while
(!feof($file))
{
echo
fgetc($file);
}
fclose($file);
?>
File
System
Functions
{Refer:
PHP
_
FILE_SYSTEM
_
FUNCTIONS.}
~