Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 87

Page |1

INTRODUCTION
What is PHP
 PHP is a recursive acronym for "PHP: Hypertext Preprocessor".

 PHP is a server side scripting language that is embedded in HTML. It is used to


manage dynamic content, databases, session tracking, even build entire e-
commerce sites.

 It is integrated with a number of popular databases, including MySQL,


PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.

 PHP is pleasingly zippy in its execution, especially when compiled as an Apache


module on the Unix side. The MySQL server, once started, executes even very
complex queries with huge result sets in record-setting time.

 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and
CORBA), making n-tier development a possibility for the first time.

 PHP is forgiving: PHP language tries to be as forgiving as possible.

 PHP Syntax is C-Like.

Common uses of PHP


 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, through
email you can send data, return data to the user.

 You add, delete, modify elements within your database through PHP.

 Access cookies variables and set cookies.

 Using PHP, you can restrict users to access some pages of your website.

 It can encrypt data.


Page |2

CHARACTERISTICS

Characteristics of PHP
Five important characteristics make PHP's practical nature possible −

 Simplicity

 Efficiency

 Security

 Flexibility

 Familiarity

PHP Features
There are given many features of PHP.

o Performance: Script written in PHP executes much faster then those scripts written
in other languages such as JSP & ASP.
o Open Source Software: PHP source code is free available on the web, you can
developed all the version of PHP according to your requirement without paying any
cost.
o Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX
operating system. A PHP application developed in one OS can be easily executed in
other OS also.
o Compatibility: PHP is compatible with almost all local servers used today like
Apache, IIS etc.
o Embedded: PHP code can be easily embedded within HTML tags and script.
Page |3

History
History of the Language
Originally (it is believed) the letters stood for Personal Home Page. The first
work was done by Rasmus Lerdorf and dates back to about 1994. Lerdorf
originally used it for his personal page – specifically to track visitors. Soon, a
lot of additional functions were added. It took a few years, though, for it to
become a language and not just a set of tools.

The code was released in the mid-1990s. Israel’s Andi Gutmans and Zeev
Suraski did a major overhaul in 1997 with the goal of using PHP to run an
eCommerce site. Their version, termed PHP 3.0, had more of the features
we expect and see today.

The same duo later created Version 4.0. 2004 saw another major revision,
PHP 5.0. Although there has not yet been a 6.0, there have been significant
improvements since 5.0, including the removal of several things that had
caused instability or potential security breaches.
Page |4

Output
Page |5

Example
1.<!DOCTYPE>
2.<html>
3.<body>
4.<?php
5.echo "<h2>Hello by PHP</h2>";
6.?>
7.</body>
8.</html>
Page |6

Client side vs
server side
BASIS FOR SERVER-SIDE SCRIPTING CLIENT-SIDE SCRIPTING

COMPARISON

Basic Works in the back end which could Works at the front end and

not be visible at the client end. script are visible among the

users.

Processing Requires server interaction. Does not need interaction with

the server.

Languages PHP, ASP.net, Ruby on Rails, HTML, CSS, JavaScript, etc.

involved ColdFusion, Python, etcetera.

Affect Could effectively customize the Can reduce the load to the

web pages and provide dynamic server.

websites.
Page |7

LOCAL AND REMOTE


SERVER
Local Server: It means you have a server setup on your current
machine. A local sever gives you exclusive access to data and objects in
your machine. You can create browse and modify data or objects that a
local server stores. You can also control where the data directories are
located. But when you are running a local server, an computer contacts
itself since it is running a local server and returns the data back to the
browser.

Remote Server: If the server hosting your file is in some ‘remote’


location then it is called Remote Server. Remote servers provide access
to shared data and objects in any organization to which the server
belongs. A user’s level of access depends on the security group that the
administrator assigns to the user name (client ID) that the user employs
to access the remote server. A user name and password is needed to
access the remote server. Your computer needs to contact a (remote)
server on the web and then server and send the data back to your
computer.
Page |8

STATIC VS DYNAMIC
WEBSITE
Static v Dynamic Website Design
There are basically two main types of website - static and dynamic.
A static site is one that is usually written in plain HTML and what is in the
code of the page is what is displayed to the user.

A dynamic site is one that is written using a server-side scripting language such as PHP,
ASP, JSP, or Coldfusion. In such a site the content is called in by the scripting language
from other files or from a database depending on actions taken by the user.

Relative merits of static and dynamic websites

Static sites - advantages

Flexibility is the main advantage of a static site - every page can be different if desired,
to match the layout to different content, and the designer is free to put in any special
effects that a client may ask for in a unique way on different pages. This allows theming
- for instance an author may want a different theme for a different book and associated
pages or perhaps for a series of books, in order to match the cover designs or the
context of the stories.

Cost is generally lower up-front than a dynamic site.

Static sites - disadvantages

The main problem with any static site appears when you wish to update the content.
Unless you are conversant with HTML and the design methods used in the site then you
Page |9

have to go back to the designer to have any content changes made. This may be
perfectly ok when a new page is required which needs design input, but if all you want
to do is change some text then it can be a nuisance for both client and designer.

The second main problem is scalability. If you wish to sell products on your site and you
have a lot of them then you may have to construct individual pages for each one, which
can take considerable time, effort and cost.

Costs - there are ongoing costs for updating the content.

Dynamic sites - advantages

The main advantages of dynamic sites are that by connecting them to databases you
can easily pull in information in an organised and structured way to create product
pages or categories of related products sorted in a variety of different ways depending
on how the user wants to view them.

This ability to connect to a database means that you can also create a content
management system - an interface which allows the client to input and manage data via
a web-based series of administration pages. That content can be text for their pages and
images to go along with the text, or items in their product range with categories,
specifications, short and long descriptions, images, etc. In both these cases it can be as
simple or as complex as the client requires.

There are little or no ongoing costs unless there is a change in the basic design or an
extra capability added.

Dynamic sites - disadvantages

The design of a dynamic site is more fixed than a static one because many of the pages
are essentially a template into which data and content is poured to create multiple
pages of a similar type. So for instance all your product pages will be essentially the
same page layout with different data being displayed. While some customisation
cabability can be built in it is usually quite limited, such a selecting from a set of pre-
defined options. Individual layout changes to particular pages are not usually possible.
P a g e | 10
P a g e | 11

EMBEDDING PHP
CODE IN WEB PAGES
Step 1. Launch a plain text editor and create this valid barebones HTML5
document with an empty body section

<!DOCTYPE HTML>

<html lang=“en”>

<head><meta charset=”UTF-8”>

<title>Getting Started With PHP</title></head>

<body>

</body>

</html>

Step 2. Insert tags into the body section to contain PHP code
<?php

?>

Step 3. Now insert between the PHP tags a descriptive comment and a
line of code to write content into the body section

# Write the traditional greeting.

echo ‘<h1>Hello World!</h1>’ ;

Step 4. Set the document encoding to UTF-8 format then save it as


hello.php in the Abyss server’s /htdocs folder
P a g e | 12
P a g e | 13

Step 5. Next enter the location http://localhost/hello.php into your web browser’s
address field to see Abyss serve up a web page containing content written by embedded PHP
code

Step 6. Now use your web browser’s View Source facility to see that PHP has written the
content into the body section, including the HTML <h1> </h1> heading tags
P a g e | 14

PHP BASIC
TOKENS:

A token is the basic component of source code in programming language. It is the smallest different,
individual and independent unit used in any programming language. Token plays an important role in
the development of a program. The different types of token used in PHP an:

 Keywords
 Identifiers
 Constants
 Operators
 Strings etc

Variable
A variable is a name given to storage area that may be used to store a data
value. A variable is a name that carrier a value with it. Variables are those
quantities whose value vary during execution of the program. It is a way to
access computer’s memory. Variables act as a container that stores
information for later use in your scripts.

VARIABLE SCOPE: Scope can be defined as the range of availability a


variable has to the program in which it is declared. PHP variables can be
one of four scope types −

 Local variables

 Function parameters

 Global variables

 Static variables.

Local Variables
A variable declared in a function is considered local; that is, it can be
referenced solely in that function. Any assignment outside of that function
will be considered to be an entirely different variable from the one
contained in the function −
P a g e | 15

Global Variables
In contrast to local variables, a global variable can be accessed in any part
of the program. However, in order to be modified, a global variable must be
explicitly declared to be global in the function in which it is to be modified.
This is accomplished, conveniently enough, by placing the keyword GLOBAL
in front of the variable that should be recognized as global. Placing this
keyword in front of an already existing variable tells PHP to use the variable
having that name

Constants
A constant is a name or an identifier for a simple value. A constant value
cannot change during the execution of the script. By default, a constant is
case-sensitive. By convention, constant identifiers are always uppercase. A
constant name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores. If you have defined a constant, it can
never be changed or undefined.

To define a constant you have to use define() function and to retrieve the
value of a constant, you have to simply specifying its name. Unlike with
variables, you do not need to have a constant with a $. You can also use
the function constant() to read a constant's value if you wish to obtain the
constant's name dynamically.

constant() function
As indicated by the name, this function will return the value of the constant.

This is useful when you want to retrieve value of a constant, but you do not
know its name, i.e. It is stored in a variable or returned by a function.
P a g e | 16

PHP Data Types


PHP data types are used to hold different types of data or values. PHP supports 8 primitive
data types that can be categorized further in 3 types:

1. Scalar Types
2. Compound Types
3. Special Types

PHP Data Types: Scalar Types


There are 4 scalar data types in PHP.

1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types


There are 2 compound data types in PHP.

1. array
2. object

PHP Data Types: Special Types


There are 2 special data types in PHP.

1. resource
2. NULL
P a g e | 17

OPERANDS AND
OPERATORS precedence
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and
5 are called operands and + is called operator. PHP language supports
following type of operators.

 Arithmetic Operators

 Comparison Operators

 Logical (or Relational) Operators

 Assignment Operators

 Conditional (or ternary) Operators

Lets have a look on all operators one by one.

Arithmetic Operators
There are following arithmetic operators supported by PHP language −

Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example

+ Adds two operands A + B will give


30

- Subtracts second operand from the first A - B will give -


10

* Multiply both operands A * B will give


200
P a g e | 18

/ Divide numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an B % A will give 0


integer division

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by A-- will give 9


one

Comparison Operators
There are following comparison operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example

== Checks if the value of two operands are equal or not, (A == B) is


if yes then condition becomes true. not true.

!= Checks if the value of two operands are equal or not, (A != B) is


if values are not equal then condition becomes true. true.

> Checks if the value of left operand is greater than the (A > B) is not
value of right operand, if yes then condition becomes true.
true.

< Checks if the value of left operand is less than the (A < B) is
value of right operand, if yes then condition becomes true.
true.
P a g e | 19

>= Checks if the value of left operand is greater than or (A >= B) is


equal to the value of right operand, if yes then not true.
condition becomes true.

<= Checks if the value of left operand is less than or (A <= B) is


equal to the value of right operand, if yes then true.
condition becomes true.

Logical Operators
There are following logical operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then −

Show Examples

Operator Description Example

and Called Logical AND operator. If both the operands are (A and B) is
true then condition becomes true. true.

or Called Logical OR Operator. If any of the two operands (A or B) is


are non zero then condition becomes true. true.

&& Called Logical AND operator. If both the operands are (A && B) is
non zero then condition becomes true. true.

|| Called Logical OR Operator. If any of the two operands (A || B) is


are non zero then condition becomes true. true.

! Called Logical NOT Operator. Use to reverses the logical !(A && B) is
state of its operand. If a condition is true then Logical false.
NOT operator will make false.

Assignment Operators
There are following assignment operators supported by PHP language −
P a g e | 20

Show Examples

Operator Description Example

= Simple assignment operator, Assigns values C = A + B will


from right side operands to left side operand assign value of A +
B into C

+= Add AND assignment operator, It adds right C += A is equivalent


operand to the left operand and assign the to C = C + A
result to left operand

-= Subtract AND assignment operator, It subtracts C -= A is equivalent


right operand from the left operand and assign to C = C - A
the result to left operand

*= Multiply AND assignment operator, It multiplies C *= A is equivalent


right operand with the left operand and assign to C = C * A
the result to left operand

/= Divide AND assignment operator, It divides left C /= A is equivalent


operand with the right operand and assign the to C = C / A
result to left operand

%= Modulus AND assignment operator, It takes C %= A is


modulus using two operands and assign the equivalent to C = C
result to left operand %A

Conditional Operator
There is one more operator called conditional operator. This first evaluates
an expression for a true or false value and then execute one of the two
given statements depending upon the result of the evaluation. The
conditional operator has this syntax −

Show Examples
P a g e | 21

Operator Description Example

?: Conditional If Condition is true ? Then value X : Otherwise


Expression value Y

Operators Categories
All the operators we have discussed above can be categorised into following
categories −

 Unary prefix operators, which precede a single operand.

 Binary operators, which take two operands and perform a variety of arithmetic
and logical operations.

 The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of
the first expression.

 Assignment operators, which assign a value to a variable.

Precedence of PHP Operators


Operator precedence determines the grouping of terms in an expression.
This affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator −

For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator


* has higher precedence than + so it first get multiplied with 3*2 and then
adds into 7.

Here operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.

Category Operator Associativity

Unary ! ++ -- Right to left


P a g e | 22

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= Right to left


P a g e | 23

COMMENTS
PHP comments can be used to describe any line of code so that other developer can
understand the code easily. It can also be used to hide any code.

PHP supports single line and multi line comments. These comments are similar to C/C++
and Perl style (Unix shell style) comments.

PHP Single Line Comments


There are two ways to use single line comments in PHP.

o // (C++ style single line comment)


o # (Unix Shell style single line comment)

1. <?php
2. // this is C++ style single line comment
3. # this is Unix Shell style single line comment
4. echo "Welcome to PHP single line comments";
5. ?>

PHP Multi Line Comments


In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within
/* */. Let's see a simple example of PHP multiple line comment.

1. <?php
2. /*
3. Anything placed
4. within comment
5. will not be displayed
6. on the browser;
7. */
8. echo "Welcome to PHP multi line comment";
9. ?>
P a g e | 24

Echo and print


PHP Echo
PHP echo is a language construct not a function, so you don't need to use parenthesis with
it. But if you want to use more than one parameters, it is required to use parenthesis.

The syntax of PHP echo is given below:

1. void echo ( string $arg1 [, string $... ] )

PHP echo statement can be used to print string, multi line strings, escaping characters,
variable, array etc.

PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with
the argument list. Unlike echo, it always returns 1.

The syntax of PHP print is given below:

1. int print(string $arg)

PHP print statement can be used to print string, multi line strings, escaping characters,
variable, array etc.
P a g e | 25

FLOWCHART
P a g e | 26

DECISION MAKING
The if, elseif ...else and switch statements are used to take decision based
on the different condition.

You can use conditional statements in your code to make your decisions.
PHP supports following three decision making statements –

 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

 elseif statement − is used with the if...else statement to


execute a set of code if one of the several condition is true

 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.
P a g e | 27

OUTPUT
P a g e | 28

The If...Else Statement


If you want to execute some code if a condition is true and another code if
a condition is false, use the if....else statement.

Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if 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>
P a g e | 29

OUTPUT
P a g e | 30

The ElseIf Statement


If you want to execute some code if one of the several conditions are true
use the elseif statement

Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
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>
P a g e | 31

Output
P a g e | 32

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;
}
Example

The switch statement works in an unusual way. First it evaluates given


expression then seeks a lable 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 lable matches then statement will execute any
specified default code.

<html>

<body>

<?php

$d = date("D");
P a g e | 33

switch ($d){

case "Mon":

echo "Today is Monday";

break;

case "Tue":

echo "Today is Tuesday";

break;

case "Wed":

echo "Today is Wednesday";

break;

case "Thu":

echo "Today is Thursday";

break;

case "Fri":

echo "Today is Friday";

break;

case "Sat":

echo "Today is Saturday";

break;

case "Sun":

echo "Today is Sunday";

break;
P a g e | 34

default:echo "Wonder which day is this ?";

?>

</body>

</html>
P a g e | 35

LOOPS and types


Loops in PHP are used to execute the same block of code a specified
number of times. PHP supports following four loop types.

 for − loops through a block of code a specified number of times.

 while − loops through a block of code if and as long as a


specified condition is true.

 do...while − loops through a block of code once, and then


repeats the loop as long as a special condition is true.

 foreach − loops through a block of code for each element in an


array.

We will discuss about continue and break keywords used to control the
loops execution.
P a g e | 36

FLOWCHART
P a g e | 37

The for loop statement


The for statement is used when you know how many times you want to
execute a statement or a block of statements.

Syntax
for (initialization; condition; increment){
code to be executed;
}

The initializer is used to set the start value for the counter of the number of
loop iterations. A variable may be declared here for this purpose and it is
traditional to name it $i.

Example
The following example makes five iterations and changes the assigned value
of two variables on each pass of the loop −

<html>

<body>

<?php

$a = 0; $b = 0;

for( $i = 0; $i<5; $i++ ) {

$a += 10; $b += 5;

echo ("At the end of the loop a = $a and b = $b" );

?>

</body>

</html>
P a g e | 38

FLOWCHART
P a g e | 39

The while loop statement


The while statement will execute a block of code if and as long as a test
expression is true.

If the test expression is true then the code block will be executed. After the
code has executed the test expression will again be evaluated and the loop
will continue until the test expression is found to be false.

Syntax
while (condition) {
code to be executed;
}
Example
This example decrements a variable value on each iteration of the loop and
the counter increments until it reaches 10 when the evaluation is false and
the loop ends.

<html>

<body>

<?php

$i = 0; $num = 50;

while( $i < 10) {

$num--; $i++;

echo ("Loop stopped at i = $i and num = $num" );

?>

</body>

</html>
P a g e | 40

OUTPUT
P a g e | 41

The do...while loop statement


The do...while statement will execute a block of code at least once - it then
will repeat the loop as long as a condition is true.

Syntax
do {
code to be executed;
}
while (condition);
Example
The following example will increment the value of i at least once, and it will
continue incrementing the variable i as long as it has a value of less than 10

<html>

<body>

<?php

$i = 0; $num = 0;

do {

$i++;

while( $i < 10 );

echo ("Loop stopped at i = $i" );

?>

</body>

</html>
P a g e | 42

OUTPUT
P a g e | 43

The foreach loop statement


The foreach statement is used to loop through arrays. For each pass the
value of the current array element is assigned to $value and the array
pointer is moved by one and in the next pass next element will be
processed.

Syntax
foreach (array as value) {
code to be executed;
}
Example
Try out following example to list out the values of an array.

<html>

<body>

<?php

$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value ) {

echo "Value is $value <br />";

?>

</body>

</html>
P a g e | 44

FUNCTION
PHP Functions
PHP function is a piece of code that can be reused many times. It can take
input as argument list and return value. There are thousands of built-in
functions in PHP.

In PHP, we can define Conditional function, Function within


Function and Recursive function also.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked
many times, like in other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic
many times. By the use of function, you can write the logic only once and
reuse it.

Easy to understand: PHP functions separate the programming logic. So it


is easier to understand the flow of the application because every logic is
divided in the form of functions.
P a g e | 45

PHP User-Defined Functions


In addition to the built-in functions, PHP also allows you to define
your own functions. It is a way to create reusable code packages
that perform specific tasks and can be kept and maintained
separately form main program. Here are some advantages of
using functions:
 Functions reduces the repetition of code within a program —
Function allows you to extract commonly used block of code into
a single component. Now you can perform the same task by
calling this function wherever you want within your script without
having to copy and paste the same block of code again and again.
 Functions makes the code much easier to maintain — Since a
function created once can be used many times, so any changes
made inside a function automatically implemented at all the
places without touching the several files.
 Functions makes it easier to eliminate the errors — When the
program is subdivided into functions, if any error occur you know
exactly what function causing the error and where to find it.
Therefore, fixing errors becomes much easier.
 Functions can be reused in other application — Because a
function is separated from the rest of the script, it's easy to reuse
the same function in other applications just by including the php
file containing those functions.

The following section will show you how easily you can define
your own function in PHP.
P a g e | 46

OUTPUT
P a g e | 47

Creating and Invoking Functions


The basic syntax of creating a custom function can be give with:
function functionName(){
// Code to be executed
}

The declaration of a user-defined function start with the


word function, followed by the name of the function you want to
create followed by parentheses i.e. () and finally place your
function's code between curly brackets {}.
This is a simple example of an user-defined function, that display
today's date:

Example
<?php
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>
P a g e | 48

FORMAL VS ACTUAL
PARAMETER
Actual vs Formal Parameters

The Actual
parameters are
the values that The Formal Parameters are the variables defined by the
are passed to the function that receives values when the function is called.
function when it
is invoked.

Related Function

The actual
parameters are
The formal parameters are in the called function.
passed by the
calling function.

Data Types

In actual
parameters,
there is no
In formal parameters, the data types of the receiving values
mentioning of
should be included.
data types. Only
the value is
mentioned.
P a g e | 49

OUTPUT
P a g e | 50

PHP Recursive Function


PHP also supports recursive function call like C/C++. In such case, we call
current function within function. It is also known as recursion.

It is recommended to avoid recursive function call over 200 recursion level


because it may smash the stack and may cause the termination of script.

Example 1: Printing number


1. <?php
2. function display($number) {
3. if($number<=5){
4. echo "$number <br/>";
5. display($number+1);
6. }
7. }
8.
9. display(1);
10.?>
P a g e | 51

LIBRARY FUNCTION
Library function are the in-built function in PHP which are used to perform a specific task. PHP comes
standard with many function and constructos. A library function is accessed by simply writing the
function name, followed by a list of arguments, which represents the information being passed to the
function, The arguments must be enclosed in parentheses and separated by commas they can be
constants variable or more complex expressions, Note that the parentheses must be represents even
when these are so arguments.

Function Description

addcslashes() Returns a string with backslashes in front of the specified characters

addslashes() Returns a string with backslashes in front of predefined characters

bin2hex() Converts a string of ASCII characters to hexadecimal values

chop() Removes whitespace or other characters from the right end of a string

chr() Returns a character from a specified ASCII value

chunk_split() Splits a string into a series of smaller parts


P a g e | 52

convert_cyr_string() Converts a string from one Cyrillic character-set to another

convert_uudecode() Decodes a uuencoded string

convert_uuencode() Encodes a string using the uuencode algorithm

count_chars() Returns information about characters used in a string

crc32() Calculates a 32-bit CRC for a string


P a g e | 53

STRING
PHP String
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4
ways to specify string in PHP.

o single quoted
o double quoted
o heredoc syntax
o newdoc syntax (since PHP 5.3)

Single Quoted PHP String


We can create a string in PHP by enclosing text in a single quote. It is the easiest way to
specify string in PHP.

1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>

Double Quoted PHP String


In PHP, we can specify string through enclosing text within double quote also. But escape
sequences and variables will be interpreted using double quote PHP strings.

1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>
P a g e | 54

INTERPOLATION
Variable interpolation is adding variables in between a string data. PHP will
parse the interpolated variables and replace the variable with its value while
processing the string data. The variable parsing is allowed with the string data
enclosed with double quotes or with heredocs. Since, the variable interpolation
will not be effective with the single quoted string or nowdocs, since it doesn’t
support variable parsing.

Variable Interpolation in a String


The following code shows an example for interpolating variable into a string
that is enclosed in double quotes. In this example, I have a string variable
containing the value ‘PHPPOT’ which is interpolated into the echo statement
to parse this variable on printing data to the browser. In this program, I
interpolated the variable in a single quoted string and shows the resultant
string with the PHP variable as it is without parsing its value.

$name = "PHPPOT";

echo "I am reading $name"; // output: I am reading PHPPOT

echo 'I am reading $name'; // output: I am reading $name


P a g e | 55

CHARACTER AND
STRING INDEXES
In some programming language there are different data types for character and strings. In PHP
there is no distinct character type different from the string type. PHP takes character argument
as a string of 1 length. In PHP, you can retrieve the individual character of a string by including
the number of character m starting at 0, enclosed in curly braces { } immediately followed by a
string variable.

<httml>

<head>

<title> representing characters </title>

</head>

<body>

<h1> Representing individual character </h1>

<?php

$my_string= “programming”

echo “The string is ”.$my_string “<br>” ;

for($index =0; index<11; index++)

$character = $my_string($index);

Echo “character” , $index+1”, is <B>$character </B> <br>”;

?>
P a g e | 56

</body>

</html>
P a g e | 57

OPERATORS
PHP String Operators
PHP has two operators that are specially designed for strings.

OPERATOR Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of $txt1 and


$txt2

.= Concatenation $txt1 .= Appends $txt2 to $txt1


assignment $txt2
P a g e | 58

Heredoc
In order to allow people to easily write large amounts of text from within PHP, but
without the need to constantly escape things, heredoc syntax was developed. Heredoc
might be a little tricky to understand at first, but it's actually a big help. Put simply, it
allows you to define your own string limiter so that you can make it something other
than a double or single quote. So, for example, we could use the string "EOT" (end of
text) for our delimiter, meaning that we can use double quotes and single quotes freely
within the body of the text - the string only ends when we type EOT.
It is a little more complicated than that in practice, but not much - the string delimiter
needs to be by itself on a line, in the very first column. That is, you cannot add spacing
or tabs around it.
Take a look at this example:
<?php

$mystring = <<<EOT This is some PHP text.

It is completely free

I can use "double quotes"

and 'single quotes',

plus $variables too, which will

be properly converted to their values,

you can even type EOT, as long as it

is not alone on a line, like this: EOT;

?>
P a g e | 59

String Functions
These are functions that manipulate string data, refer to the article on strings for
implementation examples of string functions

Function Description

addcslashes() Returns a string with backslashes in front of the


specified characters

addslashes() Returns a string with backslashes in front of predefined


characters

bin2hex() Converts a string of ASCII characters to hexadecimal


values

chop() Removes whitespace or other characters from the right


end of a string

chr() Returns a character from a specified ASCII value

chunk_split() Splits a string into a series of smaller parts

convert_cyr_string() Converts a string from one Cyrillic character-set to


another
P a g e | 60

Formatting Strings
There's a pair of string functions that are particularly useful when you want to format
data for display (such as when you're formatting numbers in string
form): printf and sprintf. The printf function echoes text directly, and you assign
the return value of sprintf to a string. Here's how you use these functions (items in
square brackets, [ and ], in function specifications like this one are optional):

printf (format [, args])

sprintf (format [, args])

The format string is composed of zero or more directives: characters that are copied
directly to the result, and conversion specifications. Each conversion specification
consists of a percent sign (%), followed by one or more of these elements, in order:

 An optional padding specifier that indicates which character should be used to pad
the results to the correct string size. This may be a space character or a 0 (zero
character). The default is to pad with spaces.
 An optional alignment specifier that indicates whether the results should be left-
justified or right-justified. The default is right-justified (a - character here will make it
left-justified).
 An optional number, the width specifier, specifying how many characters
(minimum) this conversion should result in.
 An optional precision specifier that indicates how many decimal digits should be
displayed for floating-point numbers. (There is no effect for types other
than float.)
 A type specifier that says what type the argument data should be treated as.

% A literal percent character. No argument is required.

b The argument is treated as an integer, and presented as a binary


number.

c The argument is treated as an integer, and presented as the character


P a g e | 61

with that ASCII value.

d The argument is treated as an integer, and presented as a (signed)


decimal number.

u The argument is treated as an integer, and presented as an unsigned


decimal number.

f The argument is treated as a float, and presented as a floating-point


number.

- The argument is treated as an integer, and presented as an octal


number.

s The argument is treated as and presented as a string.

x The argument is treated as an integer and presented as a hexadecimal


number (with lowercase letters).

X The argument is treated as an integer and presented as a hexadecimal


number (with uppercase letters).

+-
P a g e | 62

ARRAY
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 c 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

Advantage of PHP Array


 Less Code: We don't need to define multiple variables.
 Easy to traverse: By the help of single loop, we can traverse all the elements of an
array.
 Sorting: We can sort the elements of array.

Create an Array in PHP


 In PHP, the array() function is used to create an array:
 array();
P a g e | 63

OUTPUT
P a g e | 64

Numeric Array
These arrays can store numbers, strings and any object but their index will
be represented 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. This function is


explained in function reference.

<html>

<body>

<?php

/* First method to create array. */

$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {

echo "Value is $value <br />";

/* Second method to create array. */

$numbers[0] = "one";

$numbers[1] = "two";

$numbers[2] = "three";

$numbers[3] = "four";

$numbers[4] = "five";

foreach( $numbers as $value ) {

echo "Value is $value <br />";


P a g e | 65

?>

</body>

</html>
P a g e | 66

OUTPUT
P a g e | 67

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.

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 />";


P a g e | 68

/* 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>
P a g e | 69

OUTPUT
P a g e | 70

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.

<html>

<body>

<?php

$marks = array(

"mohammad" => array (

"physics" => 35,

"maths" => 30,

"chemistry" => 39

),

"qadir" => array (

"physics" => 30,

"maths" => 32,

"chemistry" => 29
P a g e | 71

),

"zara" => array (

"physics" => 31,

"maths" => 22,

"chemistry" => 39

);

/* Accessing multi-dimensional array values */

echo "Marks for mohammad in physics : " ;

echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";

echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;

echo $marks['zara']['chemistry'] . "<br />";

?>

</body>

</html>
P a g e | 72

output
P a g e | 73

Accessing array
elements
Array elements can be accessed using the array[key] syntax.

Accessing array elements

<html>

<head> </head>

<body>

<?php

$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)0
)
);

var_dump($array["foo"]);

var_dump($array[42]);

var_dump($array["multi"]["dimensional"]["array"]);
?>

</body>

</httml>
P a g e | 74

OUTPUT
P a g e | 75

DELELTE FROM ARRAY


Delete one array element
If you want to delete just one array element you can use unset() or
alternative array_splice().

Also if you have the value and don't know the key to delete the element you can
use array_search()to get the key.

unset() method
Note that when you use unset() the array keys won't change/reindex. If you
want to reindex the keys you can use array_values() after unset()which will
convert all keys to numerical enumerated keys starting from 0.

<html>

<head>

</head>

<body>

<h1> Deleting array from array </h1>

<?php

$cars=array(0=> "Suzuki Drive",

1=> "Hyundai Verna",

2=> "Honda City");

print_r($cars);

unset($cars[1]); //deleting second element

echo "<br>";

print_r($cars);

?>

</body> </html>
P a g e | 76

OUTPUT
P a g e | 77

CURRENT FUNCTION
current() Function
The current() function is an inbuilt function in PHP.
 It is used to return the value of the element in an array which the internal pointer is currently
pointing to.
 The current() function does not increment or decrement the internal pointer after returning
the value.
 In PHP, all arrays have an internal pointer. This internal pointer points to some element in that array
which is called as the current element of the array.
 Usually, the current element is the first inserted element in the array.
<html>

<head>

</head>

<body>

<h1> Current Function </h1>

<?php

$fruit=array("mangp","guava","grapes");

echo current($fruit);

?>

</body>

</html>
P a g e | 78

OUTPUT
P a g e | 79

NEXT FUNCTION
PHP next() Function
The next() function is an inbuilt function in PHP and does the following
operations:
 It is used to return the value of the next element in an array which the
internal pointer is currently pointing to. We can know the current
element by current function.
 The next() function increments the internal pointer after returning the
value.
 In PHP, all arrays have an internal pointer. This internal pointer points
to some element in that array which is called as the current element of
the array.
 Usually, the next element at the beginning is the second inserted
element in the array.
<html>

<head>

</head>

<body>

<h1> Next Function </h1>

<?php

$fruit=array("mango","guava","grapes","orange");

echo "The current element is ",current($fruit), "<br>";

echo "The next element is ",next($fruit), "<br>";

echo "Now The current element is ",current($fruit),


"<br>";

echo "Now The next element is ",next($fruit), "<br>";

echo "Now The current element is ",current($fruit),


"<br>";
P a g e | 80

echo "Now The next element is ",next($fruit), "<br>";

echo "Now The current element is ",current($fruit),


"<br>";

echo "Now The next element is ",next($fruit), "<br>";

?>

</body>

</html>
P a g e | 81

OUTpUT
P a g e | 82

PREV
PHP prev() Function
The prev() function is an inbuilt function in PHP.
 It is used to return the immediate previous element from an array of the element
which is currently pointed by the internal pointer.
 We have already discussed current() function in PHP.
 The current() function is used to return the value of the element which is currently
pointed by the internal pointer whereas the prev() function decrements or make the
internal pointer to point to the previous element of the currently pointed element.

<html>

<head>

</head>

<body>

<h1> Prev Function </h1>

<?php

$fruit=array("mango", "guava" ,"grapes", "orange");

echo "The current element is ",current($fruit), "<br>";

echo "The next element is ",next($fruit), "<br>";

echo "Now The previous element is ",prev($fruit), "<br>";

echo "Now The current element is ",current($fruit), "<br>";

?>

</body>

</html>
P a g e | 83

OUTPUT
P a g e | 84

RESET
PHP reset() Function
The reset() function is an inbuilt function in PHP.

 This function is used to move any array’s internal pointer to the first element of
that array.
 While working with arrays, it may happen that we modify the internal pointer of an array using
different functions like prev() function, current() function, key() function etc.
 The reset() function resets the internal pointer to point to the first element of the array.
Example

<html>

<head>

</head>

<body>

<h1>Reset Function </h1>

<?php

$fruit=array("mango","guava","grapes","orange");

echo "The current element is ",current($fruit), "<br>";

echo "The next element is ",next($fruit), "<br>";

echo "Now The current element is ",current($fruit),


"<br>";

echo "Now The next element is ",next($fruit), "<br>";

echo "Now The current element is ",current($fruit),


"<br>";

echo "Now The next element is ",next($fruit), "<br>";

echo "Again the first element is ", reset($fruit), "<br>";


P a g e | 85

?>

</body>

</html>
P a g e | 86

OUTPUT
P a g e | 87

END
PHP | end() Function
The end() function is an inbuilt function in PHP and is used to find
the last element of the given array. The end() function changes
the internal pointer of an array to point to the last element and
returns the value of the last element.

<html>

<head>

</head>

<body>

<h1> End Function </h1>

<?php

$fruit=array("mango","guava","grapes","orange");

echo "The current element is ",current($fruit), "<br>";

echo "The next element is ",next($fruit), "<br>";

echo "Now The current element is ",current($fruit), "<br>";

echo "Now The next element is ",next($fruit), "<br>";

echo "Again the last element is ", end($fruit), "<br>";

?>

</body>

</html>

You might also like