Sunteți pe pagina 1din 74

Learning Objectives

At the end of this unit, you will be able to:

Understand what is PHP


Install the PHP software and learn how to use the same
Understand the basic syntax and data types supported in PHP
Create a Sample PHP page and execute it on the Server

Introduction to PHP
What is PHP?

PHP:

stands for Hypertext Preprocessor


is a server-side scripting language
supports many different databases
is an open source software

PHP is a powerful tool to create interactive web application.

Apart from the normal text and HTML tags placed in a web page, a PHP file cont ains
commands that are executed on the server side. The server executes these commands
before it renders the response page to the user.

When a URL is typed on the browser for a PHP page, the following occurs

A request is sent to the browser requesting for that page


The server executes the PHP scripts on that file if any and sends the response to
the browser
The browser executes the HTML tags in that page and renders the response to
the end user

Support for Database


A Web Application normally requires data to be made persistent for accessing and
manipulating it in the future.

A typical web application scenario would be an Online Shopping Cart application, which
maintains its customers information and allows them to shop products online.

PHP supports many databases like MYSQL, Oracle, Sybase, Informix, etc.
PHP Installation
The most preferred method to install PHP is by using the WAMP (Windows, Apache,
MySQL, and PHP) server since it provides an all-in-one solution.

WampServer 2.0i for Windows Platform includes

Apache 2.2.11
MySQL 5.1.36
PHP 5.3.0

To download the WAMP server http://www.wampserver.com/en/#download-wrapper

To download Lamp (Linux, Apache, MySQL, PHP) server for Linux


Platform http://lamphowto.com

Have a Web Server already?

If you already have a Web Server that supports PHP

Install PHP

Download PHP for free here: http://www.php.net/downloads.php

Install any database supported by PHP, for example MySQL

Download MySQL for free here:http://www.mysql.com/downloads/


Download Apache for free here:http://httpd.apache.org/download.cgi

Working with PHP


http://www.homeandlearn.co.uk/php/php1p3.html

We will be referring the wamp server for working with PHP throughout this book

Download the WAMP server


Run the installation wizard and follow the instructions to install the WAMP server
By default the WAMP server will be installed in the C:/ drive, i.e. C:/wamp. , If we have not
mentioned any other folder during installation

After Installing the Wamp Server, the following icon appears in the bottom right corner of the task
bar

The wamp server icon can be

Partially red
Partially yellow
White
Initially the icon will be partially red. This means no service is currently running. If we click on the
wamp server icon a pop up menu will appear as follows. Select the Start all services option.

The color of the icon should now change to white, which means all service s are currently running.
If the color of the icon is partially yellow, then not all services are running which means that either
the Apache or MYSQL service hasnt started. To start them

Apache or MYSQL service hasn't started. To start them

Click on the wamp server icon, select Apache->Service->Start/Resume service


Click on the wamp server icon, select MySQL->Service->Start/Resume service

To ensure that the server is running, click on the wamp server icon and select Localhost.The
homepage of the wamp server should be displayed on the web browser as follows

To run a Sample PHP Program

Create a folder called PHP Programs in c:\wamp\www folder


Create a file called MyFirstPhp.php file and type the following code

<?php print "PHP is a Server-side HTML embedded scripting language"; ?>

To execute the PHP program;


Click on the Wamp server icon and select Localhost. We will now have the folder called PHP
displayed on the wamp servers home page.
Click on the PHP folder under Your Projects. The PHP files available in that folder will be
displayed. Click on the MyFirstPHP.php file. We can see the following output on the web browser.

Why PHP?
PHP:

runs on many different operating system platforms (Windows, Linux, Unix, etc.)
is compatible with almost all servers available and used today (Apache, IIS, etc.)
is free of cost and can be downloaded from the official PHP resource: www.php.net
is an open source software where we are free to add or modify the features of the software
syntax is based on programming languages like C and PERL.
is easy to learn and it runs efficiently on the server side

Basic Syntax of PHP


PHP file normally contains HTML tags and PHP Scripting tags

PHP Scripting Elements should be enclosed within

<?php

?>

Example1.1: Display a Message in the Web Browser

<?php

echoWelcome to PHP Programming!!!!

?>
Output on the Web Browser

Php Statement terminator and Case insensitivity


Every Statement in PHP has to be terminated by a semicolon
<?php
echo "PHP Learning time";
echo "All statements have to be terminated by a semicolon(;)";
?>
PHP keywords and function names are case insensitive
The following statements convey the same meaning to the PHP interpreter
echo strlen("hello");
echo STRLEN("hello");
ECHO strLEN("hello");

Embedding PHP in HTML


A PHP code can be embedded in HTML using the PHP Scripting block <?php ?>
<html>
<font color="red">
<?php echo "PHP is a HTML embedded scripting language ";
echo "<br>"
</font>
</html>

The message will be displayed on the Web Browser in Red.

Alternatively a PHP scripting block can also include the HTML tag enclosed within
quotes (single or double)
<html>
<font color="red">
<?php
echo "PHP is a HTML embedded scripting language";
echo "<br>";
echo "It is used to create dynamic web pages";
?>
</font>
</html>

There can be multiple PHP Blocks within the same file. The above code can also be
written as
<html>
<font color="red>
<?php
echo "PHP is a HTML embedded scripting language";
?>
<br/>
<?php
echo "It is used to create dynamic web pages";
?>
</font>
</html>

Comments
Comments are used to explain the code and make it more readable. The PHP interpreter
generally ignores comments.

PHP supports 2 types of comments

Single line comment - //

//Comments can be short and crisp.

Multi line comment - /* */

/*
This is a Multi Line Comment.

-Can be used if explanation requires more than one line

-Can be used to temporarily turn off a block of code

*/

Variables
Variables are used to store data that is manipulated throughout the program. All
Variables in PHP have to be declared using the $ symbol

Syntax for declaring a variable


$variablenam e= value

Variables in PHP need not be declared for assigning a value to it


Variables in PHP are not associated with a particular data type
PHP variables are associated with the data type depending on the value assigned
to it from time to time

Rules for Declaring a Variable

A variable name:

must start with a letter of the alphabet or an underscore "_"


can contain alpha numeric characters (a-z, A-Z, 0-9, and _)
should not contain spaces.

Assigning value to a variable


$country=India;
$order_no=122;
$course_fee=20754.75

Illegal Variable names


$+23
$12
$1ABC

Example1.2 Calculating area of a circle


<html>
<body>
<font face="arial">
<h3><b><i>Calculate Area of Circle</i></b></h3> <?php
$PI=3.14;
$area=0;
?>
<?php
$radius=3;
$area=$PI*$radius*$radius;
print "PI Value:".$PI."<br>";
print "Radius Value:".$radius."<br>";
print "Area Of Circle(PI*radius*radius) :".$area;
?>
</font>
</body>
</html>

Output on the Web Browser


Indirect reference to Variables

PHP helps us to create variables and access them by name at run time

Example 1.3: Print message to welcome the user

<?php
$name="username";
$$name="Peter";
print "Welcome ".$username;
?>

Output from the Web Browser

Constants
PHP constants are variables that have a single value through out their lifetime in the
program.

The naming rules for PHP variables applies to constants also except that they dont
have a leading $ (dollar) sign. By convention constants are declared in uppercase.
Constants have global scope, so they are accessible anywhere in the PHP scripts,
even inside functions
Although we can define cas e insensitive constants, it is recommended to use case
sensitive constants for it will be consistent and clear when used in the code

A Constant can be declared using the following syntax


define("CONSTANT_NAM E", value [, case_insensitive])
where

"CONSTANT_NAME" is a string.
value is any valid PHP expression excluding arrays and objects.
case_insensitive is a Boolean value (true/false) and is optional. The default value
is false
$purchase_amount=1000;
define ("DISCOUNT_PE RCE NT",20);
$discount_amount=$purchase_amount* DISCOUNT_PERCENT/100;
echo $discount_amount;

An example for a built-in constant is the Boolean value true, which is defined as case-
insensitive.

Managing Variables
The following language constructs helps us to

Check if variable exist


Remove variable
Check variables Truth values

isset() returns a Boolean value depending on the variables existence in a PHP


<?php
$message="hello";
if(isset($message))
print 'Variable $message exist';
else
print 'Variable $message does not exist';
echo "<br>";
if(isset($message1))
print 'Variable $message1 exist';
else
print 'Variable $message1 does not exist';
?>
unset() undeclares an already set variable, and frees any memory that was used by it.
Calling isset() on a variable that has been unset() returns false.
unset($message);
if(isset($message))
print 'Variable $message exist';
else
print 'Variable $message does not exist';

empty() is used to check if a variable has not been declared or its value is false.
Generally it is used to check if a form variable does not contain any data or it has not
been sent. The variables value will be converted to Boolean according to the rules and
then it will be checked for truth-value. The rules for Boolean Conversion will be
discussed in the Data Type section
if (empty($message))
{ print 'Sorry!! No message given';
}
The empty() method evaluates to true if $message does not contain a value that
evaluates to true.

Data Types
PHP supports 8 different data types

Integers

Integers are whole number without a decimal point


int $discount=3000

Read Formats: Integers can be read in three formats

decimal (base 10)


octal (base 8)
hexadecimal (base 16).

Decimal format is the default reading format. Octal integers are specified with a leading 0 and
hexadecimals have a leading 0x.

Note that the read format affects only how the integer is converted as it is read the value stored
in $integer_8 does not remember that it was originally written in base 8.

Range of Integer Data type

PHP integers correspond to the C long type, which in turn depends on the word-size of the
machine. For most common platforms, however, the largest integer is 2 1 (or 2,147,483,647)
and the smallest integer is (231 1) (or 2,147,483,647)

<?php
$integer_10 =-1000;
$integer_8 = 01000;
$integer_16 = 0x1000;
print "integer in decimal format (base 10): $integer_10<BR>";
print "integer in octal format (base 8): $integer_8<BR>";
print "integer in hexadecimal format (base 16): $integer_16<BR>";
?>
Output in the Web Browser

Double

Double values are floating-point numbers


$interest_rate=2.5;
$salary=170000.75;
$temp=52.6E2;

Range of Double

Range of Double is equivalent to C compilers double data type.On common platforms it has a
range of approximately 2.2E308 to 1.8E+308

Boolean

Booleans have only two possible values: TRUE and FALSE.


$status=true;

Boolean constants PHP also provides Boolean constants TRUE and FALSE

if (true)
print("print when condition is true <br>");
else
print("print when condition is false<br>");

Boolean Rules

The following are the rules by which the truth of a non-boolean value is determined

For Numbers ,all values other than zero evaluate to true and zero evaluates to false
Empty String(has zero characters) and String with the value 0 are evaluated to
false, All other Strings are evaluated to true
NULL values evaluate to false
For compound types like array or an object ,empty array and object(no values) evaluate t o
false
Array and Objects with values evaluate to true. An object contains value, if any one of its
member variable is assigned a value
Valid resources are true (although some functions that return resources when they are
successful, will return FALSE when unsuccessful).

Boolean Rules Summary


$received=0;
if($received)
print "Product shipped successfully";
else
print "Shipment is pending";
will produce the output: Shipment is pending

NULL

The type NULL takes only one possible value called NULL.NULL indicates an unassigned value,
unknown value, no value or lack of value. NULL is a PHP constant and is case insensitive.

The following assignment statements conveys the same meaning to PHP interpreter, that the des
ignation is not assigned yet

$designation=null;
$designation=NULL;

A Variable when assigned NULL

evaluates to FALSE in a Boolean context.


returns FALSE when tested with IsSet().
PHP will not give any warnings when a NULL value is passed or returned from a function.
But it might sometimes give warnings for a variable that has never been set ,if passed or
returned from a function

String

Strings are sequences of characters.

$message=Knowledge is Power!!!

Strings can be enclosed in either single or double quotation marks with a different interpretation
during read time. Singly quoted strings are treated almost literally, whereas doubly quoted strings
replace variables with their values and treat certain specially interpreted character sequences in a
different way.

Single Quoted and Double Quoted Strings

Single Quoted Strings read and store their values literally apart from treating few specially
interpreted character sequences in a different way

$message='A Clever person solves a problem. A Wise person avoids it';


print 'Albert Einstein says, $message';
The output for the above code will be
Albert Einstein says, $message

We can use a double quote within a single quote.

print 'Albert Einstein says, "A Clever person solves a problem. A Wise person avoids it"';

The output for the above code will be

Albert Einstein says, "A Clever person solves a problem. A Wise person avoids it"

To use a single quote in a single quoted string, escape it with the backslash. To escape a back
slash we can use

\\
$msg=' \' can be used with in \'\' by escaping it using \\';
print $msg;
The output for the above code will be
' can be used with in '' by escaping it using \

Here-Docs

Helps us to include large pieces of text in our scripts, which may include lots of double quotes and
single quotes, without having to escape them.

print <<<string_here
Shakespearean quotations such as "To be, or not to be" , "O Romeo, Romeo! wherefore art thou Romeo?" and "But,
for my own part, it was Greek to me" form some of literature's most celebrated lines. Many expressions that we use
every day is from William Shakespeare's plays. But we are unaware that we are 'borrowing' sayings from his work!
string_here;

The output for the above code will be

Shakespearean quotations such as "To be, or not to be" , "O Romeo, Romeo! wherefore art thou Romeo?" and "But,
for my own part, it was Greek to me" form some of literature's most celebrated lines. Many expressions that we use
every day is from William Shakespeare's plays. But we are unaware that we are 'borrowing' sayings from his work!

Ensure that the String starts with <<<, followed by a string(Example: string_here) that does not
appear in our text. It is terminated by writing that string (Example: string_here) at the beginning of
a line, followed by an optional semicolon (;), and then a required newline (\n). Escaping and
variable substitution in here-docs is identical to double-quoted strings except that we are not
required to escape them

Accessing Characters in String

Individual Characters within a string can be accessed using $str(offset) format. We can use this
notation to write and read a String.

To Write String Characters:

$msg="H";
$msg{1}="e";
$msg{2}="l";
$msg{3}="l";
$msg{4}="o";
echo $msg;

will produce the output


Hello
For reading a character in String, we should use only valid offset/index. String index starts with 0
$wish="Happy Birthday!";

Output Function

Echo and Print are the 2 the output statements available in PHP.They can be used with or without
parenthesis. The following statements prints the output on the web browser

echo "hello"; // will produce the output : hello


echo ("hello"); // will produce the output: hello

Echo

We can have Multiple Arguments for the echo, when used without parenthesis

echo "Everything is okay in the end, if it's not ok, then it's not the end.","<br> ","Never Give UP!!!";

However, echo when used with parenthesis, can accept only one argument. The above statement
produces an error when used with parenthesis

echo ("Everything is okay in the end, if it's not ok, then it's not the end.","<br>","Never Give UP!!!");

Print

The print statement is very similar to echo, with two important differences:

Unlike echo, print can accept only one argument.


Unlike echo, print returns a value, which represents whether the print statement was
successful or not.
The value returned by print will be 1 if the printing was successful and 0 if unsuccessful.
Print 24.5;
Print 'c';

Resources

Are special data type, represent a PHP extension resource such as a database query, an open
file, a database connection, and lots of other external types.

Array

An array is a collection of key/value pairs. An array maps keys (or indexes) to values. An array
index can either be an integer or string whereas the value of an array can be of any type (including
other arrays).

$fruits=array("apple","mango","grapes");
echo $fruits[0];
will display apple

Object
Objects are instances of programmer-defi ned classes, which can package both values and
functions that are specific to the class

<?php class Employee


{
var $id=0;
var $name=null;
}
$empobj=new Employee();
$empobj->id=1;
$empobj->name="Sam";
echo "Employee id:".$empobj->id;
echo <br>;
echo "Employee Name:".$empobj->name;
?>

Will produce an output on the web browser as


Employee id: 1
Employee Name: Sam

Summary
Now that you have completed this unit, you should be able to

Understand what is PHP


Install the PHP software and how to use
Understand the basic syntax and data types supported in PHP
Create a Sample PHP page and execute it on the Server

Self-Assessment Quiz
1. PHP is a --------------------------------------- language
a. Client side scripting
b. Server side scripting
c. Procedural
d. None of the above
2. PHP scripts can be embedded in HTML using
a. <phpscript phpscript>
b. <?phpscript phpscript>
c. <?php php>
d. <?php ?>
3. What is the output of the following code?

<?php
$num1=20;
$num2=30;
echo $num1.$num2
?>

a. 50
b. 60
c. 2030
d. error
4. The isset() method
a. Used to declare a variable
b. Used to undeclared a variable
c. Used to check the variables existence
d. Used to check if the variable is NULL
5. What is the output of the following code?

<?php
$value=-2;
if($value)
echo "true";
else
echo "false";
?>

a. true
b. false
c. error
6. Which of the following defines a Constant?
a. define(bonus_point,3);
b. define('bonus_point',3);
c. Define(bonus_point,3);
d. All the above
7. What is the output of the following code snippet?

$msg="H";
$msg{1}="e";
$msg{2}="l";
$msg{1}="l";
$msg{4}="o";
echo $msg;

a. Hello
b. Hllo
c. Hll o
d. Error
8. All data types in PHP can be evaluated to Boolean value
a. True
b. False
9. What is the output of the following statement?
Print("Hello Peter, Welcome to the Show!");
a. Hello Peter, Welcome to the Show!
b. "Hello Peter, Welcome to the Show!"
c. Error, because print function cannot accept multiple arguments
d. Error, because function name has to be in lowercase
10. -----------------------is an unknown or unassigned or no value in PHP
a. Empty Array
b. Object with no attributes
c. False
d. Null
Answers to Self-Assessment Quiz
1. b
2. d
3. c
4. c
5. a
6. b
7. c
8. a
9. a
10. d
Operators
Once you know of the existence of variables and constants, you can begin to operate
with them. For that purpose, PHP integrates operators. We use numerous expressions to
calculate some specific value. These expressions make use of many operators. The
variables used in these expressions are operands. Some operators need only one
operand and they are called unary operators. Operators that require two operands are
called binary operators and operators that require three operands are called ternary
operators.

Various type of operators supported by PHP are:

Arithmetic Operators
Bitwise Operators
Comparison Operators
Logical Operators
Incrementing/Decrementing Operator
Concatenation Operator

Learning Objectives

At the end of this unit, you will be able to understand:

the types of operators


how to use the precedence operator
how to execute a block of statements based on conditions and various ways to repeat a
certain task.

Arithmetic Operators
Arithmetic operators are used to indicat e arithmetic operations such as addition,

subtraction, multiplication, division and modulus.

<?php
$no1=10;
$no2=3;
echo $no1+no2;
echo $no1-no2;
echo $no1%no2;
?>

Operations of addition, subtraction, multiplication and division literally correspond with their

respective mathematical operators.

The only one that you might not have come across is modulo;

Modulo is the operation that gives the remainder of a division of two values.

In the above code snippet the output of $no1%no2 is 1.


Bitwise Operators
A bitwise operator operates on each bit of data.

These operators are used for testing, complementing or shifting bits to the right or left.

Table2.2
Comparison Operators
Comparison operators enable you to determine the relationship between two operands.

We often compare two similar quantities and depending on their relation,

take some decisions.

These comparisons can be done with the help of comparison operators.

Each of these operators compare their l eft hand side with their right hand side and evaluate

to 0 if the condition is false and 1 if it is true.

Table:2.3
Lets take two numbers 40 and 60, and find out what happens when we use different

comparison operators on them.

40<60 results in true


40>60 results in false
40<=60 results in true
40>=60 results in false
40==60 results in false
40!=60 results in true
40=='40' results in true ---> Automatic type conversion

Note: Automatic type conversion takes place for all the above comparison operators.

For the following two operators, automatic type conversions are not performed.

Table:2.4
For example, the operation 40 === '40' results in false.

Logical Operators
Logical operators are used in combination with comparison operators to determine if a
condition is true or false. The standard logical operations (AND, OR, and EXCLUSIVE-OR)
are supported by PHP.

Table:2.5
The AND operator performs logical conjunction on two Boolean expressions. If both
expressions evaluate to True, then the AND operator returns True. If any one of the
expression evaluate to False, the AND returns False. The OR operator performs logical
disjunction on two Boolean expressions. If either expression evaluates to True, OR returns
True. If neither expression evaluates to True, OR returns False. XOR performs logical
exclusion on two expressions. If either expression evaluates to True, XOR returns True.
If both expressions evaluate to True or both expressions evaluate to False, XOR returns
False.

Note: In AND if the first expression evaluates to false, it wont continue to evaluate

the second expression.

Concatenation Operator

Concatenation operators join multiple strings into a single string. The Dot operator is used

for Concatenation in PHP.

$empname=John;
$empid=1003;
echo Your Employee id is.$empid.<br>;
echo Your name.$empname,<br>;
// The above two lines can be given like this also
echo Your Employee id is.$empid.<br>Your name.$empname;
The integer $empid is internally converted to the string "1003" before it is concatenated with

the strings prefix,"Your Employee is".

Increment and Decrement Operator


PHP supports C-style pre- and post-increment and decrement operators. This operator

can be used only with variables and not directly on any value

Table:2.6

Note: The increment/decrement operators do not affect Boolean values.

Example :2.1
<?php
echo " <h3>Preincrement</h3> ";
$a = 10;
echo "Should be 10: " . $a++ . "<br />";
echo "Should be 11: " . $a . "<br />";
echo " <h3>Preincrement</h3> ";
$a = 10;
echo "Should be 11: " . ++$a . "<br />";
echo "Should be 11: " . $a . "<br />";
?>
The output of the above code:

Ternary Operator

The ternary operator "?:" earns its name because it's the only operator to take three

operands. It is a conditional operator that provides a shorter syntax for the if..then..else

statement. The first operand is a Boolean expression; if the expression is true then the

value of the second operand is returned otherwise the value of the third operand is returned.

The general syntax of this operator is:

expression?operand1:operand2

For example, the following code snippet checks whether $no1 is greater th an $no2 and

displays a result accordingly


$no1=10;
$no2=20;
$result=($no1>$no2)?"no1 is greater":"no2 is greater";
echo $result;

For the above code the output is displayed as no2 is greater.


Operator Precedence
Operator Precedence is an evaluation order in which the operators within an expression

are evaluated on basis of priority. Operators with a higher precedence are applied before

operators with a lower precedence. For example, the expression "4 + 5 * 6 / 3" will be

treated as "4 + (5 * (6 / 3))" and 14 is obtained as the result.

When two operators share an operand then the operator with the higher precedence gets

evaluated first.

When operators have equal precedence, their associativity decides whether they are

evaluated starting from the right, or starting from the left.

Table: 2.7
String Manipulation
A string is a series of characters, where a character is the same as a byte. A string literal

can be specified as:


$name=tom;

$companyname=ibm;

When writing string values in the source code, we can use double quotes (") and single

quotes (').

For example echo Personal details and echo 'Personal details' will yield the same output, except in

the following case;


$name=tom;
echo your name is $name;
echo 'your name is $name';

The output of the above code is


your name is tom
your name is $name

When double quotes is used the references to variables are automatically replaced with the

variables values, but in single quotes only the message is printed.

The various methods used to manipulate strings in PHP are:

strtoupper() Converts a string to uppercase.

Strtolower() Converts a string to lowercase.

ucfirst() Converts the first character of a string to uppercase.

ucwords() Converts the first character of each word in a string to uppercase.

strcmp() Compares two strings. Returns < 0 if str1 is less than str2, > 0 if str1 is greater

than str2, and 0 if they are equal.

strlen() Returns the length of a string.

substr(str,pos) Returns the substring from the character in position pos to the end of the

string.

trim() Removes whitespace at the beginning and end of a string.

Example :2.2
<?php
$message="PHP is a server side programming language";
echo " <h3>strtoupper</h3> ";
echo strtoupper($message);
echo " <h3>strtolower</h3> ";
echo strtolower($message);
echo " <h3>ucfirst</h3> ";
echo ucfirst($message);
echo " <h3>ucwords</h3> ";
echo ucwords($message);
echo " <h3>strlen</h3> ";
echo strlen($message);
echo " <h3>substr</h3> ";
echo substr($message,4);
?>
The output of the above code:

Control Structures
So far we have written programs that follow a sequential structure, executing one statement

after another. Using control structures we can execute a statement based on some

conditions. This helps a programmer to control the flow of program execution. In PHP the

control structures are divided into two groups:

Conditional control structures


Loop control structures.

Conditional Control Structures

The conditional control structures affect the flow of the program and execute or skip certain

code according to certain criteria .PHP supports both the if and switch conditional control

structures.
If Statement
The if construct is used when we need to decide which of the available paths is to be taken

based on a certain condition. If the condition that is checked is true, then the statements

inside the if block will get executed.

The syntax of if:


If (expression)

statements;

Example

$age=23;

if(age>=18)

echo You are eligible to vote;

In the above example the braces are optional. If you have multiple statements inside the

if block then braces are mandatory .You can also use another syntax like the one below:
$age=23;

if(age>=18):

echo You are eligible to vote;

endif;

If-else Statement

The if-else statement provides a secondary path of execution when an "if" clause evaluates

to false.

The syntax of the if-else:


if(expression)

statement;

else

statement;

Example

$age=23;
if(age>=18)

echo You are eligible to vote;

else

echo You are not eligible to vote;

If the expression evaluates to true, statements under IF are executed. If false, and there is

an else clause, statements in the else block are executed. If expression evaluates to false,

and there is no else block, execution simply proceeds with the next statement after the if

construct.

If-else if statement

By using Else If, it is possible to combine several conditions. Only the statements following

the first condition that is found to be true will be executed. All other statements are skipped.

The statements of the final Else will be executed if none of the conditions are true.

The syntax of the if-else if:


if(expression)

statement;

else if(expression)

statement;

else if(expression)

statement;

..

else

statement;

Example

$avg=50;

if($avg>=81 and $avg<=90)

$grade='O';

echo "Your grade is $grade";

else if($avg>=71 and $avg<=80)


{

$grade='A';

echo "Your grade is $grade";

else if($avg>=61 and $avg<=70)

$grade='B';

echo "Your grade is $grade";

else

$grade='C';

echo "Your grade is $grade";

Nested If

Nested If statements are if statements inside another if statement.

The syntax of the nested if is as follows:


if(expression)

if(expression)

statement;

else

statement;

else

statement;

Example

$number=90;

$value=50;
if($number!=0)

if($number>0)

$result=$value/$number;

echo "result".$result;

else

echo "give a positive number";

else

echo "You cannot divide a number by zero";

Switch Statement

Switch / case is very similar or an alternative to the if / elseif / else commands.

The switch command tests a condition. The outcome of that test dec ides which case to

execute. Switch is normally used when you are finding an exact (equal) result instead of a

greater or less than result.

The syntax of switch:


switch (expression)

case value:

statements;

break;

case value:

statements;

break;

... default:

statements;
break;

The switch condition is examined and a value is found. The condition value is passed

through the cases. If the value matches a case value, the code in that block is executed.

If the valu e does not match any of the case values, the default section is executed.

Once a block of coding is finished, the BREAK command is used to jump out of the

switch/case area.

Example

Let's imagine you own a computer retail store. Depending on the product nam e we need to

display the price of that product. Now, instead of writing separate if else statements for each

product name, we simply use the switch statement on the product name variable to evaluate

which product we want to the display the price for.

For example:
$product_name = "Processors";

switch ($product_name)

case "Video Cards":

echo "Video cards range from $50 to $500";

break;

case "Monitors":

echo "LCD monitors range from $200 to $400";

break;

case "Processors":

echo "processors range from $100 to $1000";

break;

default:

echo "Sorry, we don't carry $product_name in our catalog";

break;
}

if someone asks for a product and if it is not available in the store, in that case, the

statements in the default block get executed.

Example
$choice='y';

switch($choice)

case 'y':

echo Your choice is yes;

break;

case 'n':

echo Your choice is no; break;

default:

echo no correct match;

In the above example the user can opt for either y or n. In case the user types Y or N,

the statements in the default block will be executed. We solve this in the following manner:
$choice='y';

switch($choice)

case 'y':

case 'Y:

echo Your choice is yes;

break; case 'n': case 'N':

echo Your choice is no;

break;

default:

echo no correct match;

}
Loop Control Structures
Loop control structures execute certain code arbitrary number of times according to

specified criteria. They are used for repeating certain tasks in the program, such as iterating

over a database query result set. PHP supports for, while, do-while and for each.

For Loop

The for loop is used to perform a set of operations repeatedly until some condition is

satisfied. The syntax of a for loop is;


for(initialization:test-condition:increment/decrement)

statement; (or)

for(initialization:test-condition:increment/decrement):

statement;

endfor;

The initialization is evaluated just once, usually to initialize variables.

Then the test-condition is evaluated if false, the loop exits, and if true, the statements

inside the for loop is executed. Finally, the increment/decrement expression is executed

and the cycle begins again with the test-condition.

Figure:2.1

Example

for ($i = 0; $i < 10; $i++)


echo "The square of $i is " . $i*$i . "\n";
While Loop

The function of the while loop is to do a task over and over as long as the specified

conditional statement is true. The syntax of while loop is:


while(testcondition)
statement;
(or)
while(testcondition):
statement;
endwhile;

Example
$counter=8;
while($counter<10):
echo The counter value.$counter;

endwhile;

Do-while loop

The functionality of do-while is exactly the same as the while loop, except that the condition

in the do- while loop is evaluated after the execution of statement and not before.

This means that the loop always runs at least once. The syntax of the do-while loop is:
do
{
statements;
}while(testcondition);

Example
$choice='y';
do
{
echo "1.Display the student details";
echo "2.Add the student details";
echo "Do you want to continue";
}while($choice=='n');

The do-while is mainly used for menu-based applications.

Note: The for each loop provides an easy way to iterate over arrays (see unit-4)

Loop Control: break and continue

Sometimes, we will have to terminate the execution of a loop in the middle of an iteration.

For this purpose, PHP provides the break statement.


Example: Program to extract only the name from the emailid.
$emailid="john@ibm.com";
$length=strlen($emailid);
for($i=0;$i<$length;$i++)
{
if($emailid[$i]=='@')
{
break;
}
else
{
echo $emailid[$i];
}
}

In the above example, once an @ symbol is encountered the control comes out of the loop.

If Break appears alone, the innermost loop is stopped. Break accepts an optional argument

of the amount of nesting levels to break out of, break n; which will break from n innermost

loops (break 1; is identical to break ).

For example:
for($i=0;$i<5;$i++)
{
for($j=0;$j<5;$j++)
{
echo $i." ".$j."<br>";
if($j==3)
break 2;
}
}

In this example, once the if condition evaluates to true the control comes out of the outer

loop. Instead of break

2, if you have said just break , it will exit only from the inner loop. The output of the above

program will be 0 0, 0 1, 0 2, 0 3.

Continue

Continue is used within looping structures to skip the rest of the current loop iteration and

continue execution at the condition evaluation and then the beginning of the next iteration.

Continue also accepts an optional numeric argument which mentions how many levels of

enclosing loops it should skip to the end.


Example: A program to print only odd number from 1to 10

for($i=0;$i<10;$i++)
{
if($i%2==0)
{
continue;
}
echo $i."<br>";
}

In this example if the if statement evaluates to true, it will not execute the remaining

statements in the loop.

Problems to Solve
1. Write a program to check whether a given character is vowel or not.
2. Write a program to print whether a given number is even or odd.
3. Write a program to print the number from 1 to 100.
4. Write a program to extract each character from a string.
5. Write a program to extract each word from a string.
6. Write a program to design a calculator, which perform only addition, subtraction, multipli
7. Write a program to accept the string from the user and count the number of vowels and

8.

Summary
Now that you have completed this unit, you should be able to:

Know how operators work in PHP


Understand operator precedence and associativity
Use various control structures used in PHP
Use the break and continue statements of PHP
Learning Objective
At the end of this unit you will be able to:

Know the advantages of reusing code


Know how to write a user defined function
Understand various parts in a function.
Make use of built-in functions in PHP.
Understand the scope of variables.

Functions
A function is a self-contained block of statements that performs a specific task . Functions
are most useful when you need to use the same code in more than one place. Reusing
existing code reduces costs, increases reliability, and improves consistency. Ideally,
combining existing reusable components, with a minimum of development from scratch
creates a new project. If you find that your code files are getting longer, harder to
understand, and more difficult to manage, however, it may be an indication that you
should st art wrapping some of your code up into functions.

Some of the properties of a function:

It:

has a unique name.


is independent and it can perform its task without intervention from or interfering
with other parts of the program .
can take some inputs(i.e arguments) for performing a task.
returns a value to the calling program. This is optional and depends upon the task
your function is going to accomplish.

User Defined Function


Function Definition

To create a new function, use the function keyword. The syntax for declaring a function:
function function-name([argument1,argument2,...])

statements;

[return statement];

}
Note:Return statement and arguments are optional

Function name follow the same rules as variable name. A function may have one or many
arguments. The code (i.e statements) that will be executed each time the function is
invoked should be enclosed within the braces.

Example:
<?php
function contact_info()
{
echo "IBM<br>";
echo "No:2 Indira Nagar<br>";
echo "Mumbai-41.";
}
?>

In the above example contact_info is the name of the function. This function does not
return any value, and it does not take any arguments. W herever the contact information
is needed you can invoke this function.
Function call
We can call a function by mentioning its name followed by a pair of parentheses. If the
function takes any arguments, you place the arguments between the parentheses,
separated by commas. We can invoke the contact_info function as:
contact_info( );

What happens when a function is called?

PHP looks up the function by its name (an error appears if the function has not yet
been defined).
PHP substitutes the values of the calling arguments (or the actual parameters) into
the variables in the definitions parameter list (or the formal parameters).
The statements in the body of the function are executed. If any of the executed
statements are return statements, the function stops and returns the given value.
Otherwise, the function completes after the last statement is executed, without
returning a value

Functions can be defined before or after they are called or invoked. The PHP interpreter
reads the entire program file and takes care of all the function definitions before it runs
any of the commands in the file.

Function with arguments

As mentioned earlier a function can take some inputs (i.e arguments) for performing a
task. For example if you want to calculate an incentive amount for every employee in a
company, a function can be written like the one that follows;
Example:3.2

<?php
function calculateIncentive($salary,$incentivepercentage)
{
$incentive_amt=$salary*($incentivepercentage/100);
echo "Incentive Amount: ".$incentive_amt;
}

//To invoke or call the function

$salaryamt=25000;
$incentive_percentage=5;
calculateIncentive($salaryamt,$incentive_percentage);
>

In this example we pass salary and incentivepercentage as an input to the function,


based on the input the incentive amount is calculated. In future if the company wants to
increase the incentivepercentage,it is enough to use the incentivepercentage in the
function call. Now this can be re-used for calculating the incentive for any number of
employees.

While invoking the function calculateIncentive we passed two arguments. These


arguments are calledactual parameters and the arguments that appear in the function
declaration are called formal parameters. In the above examples, the arguments we
passed to our functions happened to be variables . The actual parameters (that is, the
arguments in the function call) may be any expression that evaluates to a value or you
can give the value alone. The above function can also be invoked as;
calculateIncentive(25000,5);

Function with Return Value

The Return statement is used to return a value or c ontrol to the calling portion of the
program. It is an optional statement. In PHP we can return values, arrays, or object s. In
example 3.2 we have printed the incentive amount in the function itself. If we have to
return the incentive amount to the calling program we can use the return statement.
Example 3.2 can be re-defined as

Example:3.3
<?php
function calculateIncentive($salary,$incentivepercentage)
{
$incentive_amt=$salary*($incentivepercentage/100);
return $Incentive Amount;
}
//To invoke or call the function
$salaryamt=25000;
$incentive_percentage=5;
$incentive_amount=calculateIncentive($salaryamt,$incentive_percentage);
echo "Incentive Amount: ".$incentive_amount;
>

In the above example if you want you can write a s eparate function for calculating the
salary as
A function call can be anywhere in the program, and it can be inside another function too.
For example the calculateIncentive function can be re-defined as
<?php
function calculateIncentive($amount,$incentivepercentage)
{
$incentive_amt=calculatesalary($amount)*($incentivepercentage/100);
return $incentive_amt;
}
//To invoke or call the function
$amount=25000;
$incentive_percentage=5;
$incentive_amount=calculateIncentive($amount,$incentive_percentage);
echo "Incentive Amount: ".$incentive_amount;
>

In the above example for calculating the incentive we need a salary amount, and so from
the calculateIncentive function we have invoked the calculatesalary function.
Call by value and References
There are two different ways of passing the arguments. The first is the most common,
which is called passing by value (or call by value), and the second is called passing
by reference (or call by references). The examples we have come across so far have
used call by value . While invoking the function we pass the value and the value is
assigned to the corresponding variable in the function. In call by references instead of
the variables value being passed, the corresponding variable in the function directly
refers to the passed variable.

Lets take a look at an example for call by value and references. We are going to write a
function for swapping two numbers.

Method 1: Call by value


<?php
function swap($no1,$no2)
{
$temp=$no1;
$no1=$no2;
$no2=$temp;
}
$a=10;
$b=20;
echo "<h3>Before Swapping<br></h3>"; echo "a:".$a."
b:".$b."<br>"; swap($a,$b);
echo "<h3>After Swapping<br></h3>";
echo "a:".$a." b:".$b."<br>"; ?>

The output of the above code:

The contents of $a and $ have not changed, this is because the code creates a variable
$a and $b with the value 10 and 20.It then calls the function swap (), variables $no1 and
$no2 are created inside the function and the values of $a and $b are copied to $no1 and
$no2 and then the swapping process happens inside the function. Now we return to the
code that called it. The swapping has happened between $no1 and $no2, which is not
reflected in $a and $b.

The better approach is to use call by reference for this problem. When a parameter is
passed to a function, instead of creating a new variable, the function receives a reference
to the original variable. This reference has a variable name, beginning with a dollar sign,
and can be used in exactly the same way as another variable. The difference is that
rather than having a value of its own, it merely refers to the original. So any modification
made to the reference will affect the original.

The above swap function can be modified as

Method 2: Call by Reference


<?php
function swap(&$no1,&$no2)
{
$temp=$no1;
$no1=$no2;
$no2=$temp;
}
$a=10;
$b=20;
echo "<h3>Before Swapping<br></h3>"; echo "a:".$a." b:".$b."<br>"; swap($a,$b);
echo "<h3>After Swapping<br></h3>";
echo "a:".$a." b:".$b."<br>";
?>

The output of the above code:

In the call by reference we placed an ampersand(&) before the parameter name in the
function's definition. No change is required in the function call.
Default Parameters

When declaring a function we can specify a default value for each of the last parameters.
This value will be used if the corresponding argument is left blank when calling the
function. To do that, we simply have to use the assignment operator and a value for the
arguments in the function declaration. If a value for that parameter is not passed when
the function is called, the default value is used, but if a value is specified this default value
is ignored and the passed value is used instead. For example:
function calculateSimpleInterest($principal,$noofyears, $interestrate=4)

$interest=$principal*$noofyears*($interestrate/100);

echo $interest;

calculateSimpleInterest(1000,5);

In the above example by default we have fixed the interest rate as 2, and while invoking
the function we have passed only the principal and no of years. We can invoke the same
as;
calculateSimpleInterest(1000,5,6);

In this case we have passed the interest rate as 6, so the default value 2 will be over-
written as 6.

Default arguments are used only in function calls where trailing arguments are omitted
they must be the last argument(s). Therefore, the following code is illegal:
function calculateSimpleInterest($principal=1000,$noofyears,$interestrate=4)

$interest=$principal*$noofyears*($interestrate/100);

echo $interest;

But we can have more than one default argument in a function, for example:
function calculateSimpleInterest($principal,$noofyears=5, $interestrate=4)

$interest=$principal*$noofyears*($interestrate/100);

echo $interest;

}
The above function can be invoked as
calculateSimpleInterest(1000);

Since we have given the default values for no of years and interest rate we need to pass
only the principal.
CalculateSimpleInterest(1000,6); // This is also a valid function call

In the above function call we have passed both the principal and no of years.
Understanding 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.

Every function has its own set of variables called local variables, which can be accessed
only within thatfunction. 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 aro und after the function call ends. The variables
that are declared outside the function are called global variables.

For example:
function myfunction()
{
$no1=10;
} $no1=20;
myfunction();
echo $no1;

When the function myfunction() is called, the variable $no1, which is assigned 10, is only in
the scope of the function and thus does not change $no1 outside the function. So the
above code snippet prints out 20.

Now suppose if we have to access or change the global variables inside the function we
can use $GLOBALS[].

$GLOBALS[]

References all variables available in global scope


It is an associative array(see Unit 4) containing references to all variables which are
currently defined in the global scope of the script. The variable names are the keys
of the array.

The above code snippet can be modified as:


function myfunction()

$GLOBALS["no1"]=10;

$no1=20;
myfunction();
echo $no1;

Now we get the output as 10. In myfunction() we have changed the global variable $no1
value to 10. Here we have used $GLOBALS[] to access the global variable.

Lets consider another example for accessing a global variable:


function add()

$no1=10;

$no2=20;

echo $no1+$no2."<br>";

echo $no1+$GLOBALS["no2"];

$no2=40;

add();

In the above code for echo $no1+$no2 it prints out 30,because for $no2 it will consider
the local variable. For echo $no1+$GLOBALS["no2"] it prints out 50,here $no2 is a global
variable.
Global Keyword
A global keyword enables us to declare what global variables we want to access, causing
them to be imported into the functions scope. Using the global declaration, we can inform
PHP that we want a variable name to mean the same thing as it does in the context
outside the function. The syntax of this declaration is simply the word global, variable
name with a terminating semicolon.

The myfunction function can be modified as


function myfunction()
{

global $no1;

$no1=10;

$no1=20;
myfunction();

echo $no1;

For the above code snippet the output would be 10. It is the same as the earlier one ,the
only difference being the use of global instead of $GLOBALS[].

Note: he keyword global can be used to manually specify that a variable defined or used
within a function has global scope.
Static Variables
On each function call local variables act as though they have been newly created. The
static declaration overrides this behavior for particular variables, causing them to retain
their values in between calls to the same function.

Example:

function display()

static $no=10;

echo $no;

$no++;

display();

display();

In the above code snippet for the first function call, 10 will be initialized to $no, the
output is printed as 10 and the value of $no is incremented to 11. For the next function
call the initialization will not happen, the output is printed as 11 and again the value of
$no is incremented. When static variables are used value initialization happens only
once. Lets consider another example for static variables:
<?php

function printnumbers()

static $count=1;

$limit=$count+10;

while($count<$limit)

echo $count."<br>";

$count++;

}
}

printnumbers();

printnumbers();

?>

The output of the above code:

Note: The use of static variables can be fully achieved only when they are declared
inside a function.

Superglobals

Several predefined variables in PHP are "superglobals", which means they are available
in all scopes throughout a script. There is no need to invoke global $variable; to
access them within functions or methods.

Some of the superglobals variables are:

$GLOBALS
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST

Include() and require()

Using include() or require()a file can be loaded into a PHP script. The file can contain
anything wewould type in a script including PHP statements, text, HTML tags, PHP
functions, PHP classes. These two statements allow to reuse any type of code and are
similar like #include in C or C++. The include() function takes all the content in a
specified file and includes it in the current file. The require() function is identical to
include(), except that it handles errors differently.

Lets see an example of how to use include() and require():

The code below is saved as depositdetails.php

<?php

echo "<h4>Interest Rates for Fixed Deposit<br></h4>";

echo "Your interest is calculated on a quarterly basis for deposits of 6 months and above<br>"; ?>

The code below is saved as loandetails.php


<?php

echo "<h4>Personal Loan Features & Benefits<br></h4>";

echo "You can Borrow up to Rs 20,00,000 for any purpose depending on your requirements.<br>";

echo "Repayment options, ranging from 10 to 60 months.<br>";

echo "If you are an bank salary account holder, we have a special offer for you";

?> </p>

Now another PHP program called bank.php is written, which uses depositdetails.php
and loandetails.php
<?php

echo "<h4>WELCOME TO STATE BANK<br></h4>";

require("depositdetails.php");
include("loandetails.php");

echo "For net banking contact the &ltbr>";

echo "corresponding bank where you have account";

?>

The output of the script bank.php:


When we run the file bank.php, the require and include statements (i.e)
require("depositdetails.php") and include("loandetails.php"); is replaced by the contents
of the requested file, and the script is then executed. When we load bank.php, it runs as
though the script were written as:

<?php

echo "<h4>WELCOME TO STATE BANK<br></h4>";

echo "<h4>Interest Rates for Fixed Deposit<br></h4>";

echo "Your interest is calculated on a quarterly basis for deposits of 6 months and above<br>";

echo "<h4>Personal Loan Features & Benefits<br></h4>";

echo "You can Borrow up to Rs 20,00,000 for any purpose depending on your requirements.<<br>";

echo "Repayment options, ranging from 10 to 60 months.<br>";

echo "If you are an bank salary account holder, we have a special offer for you";

echo "<br><br>For net banking contact the corresponding bank where you have account";

?>

Both include() and require() have the effect of placing the contents of their file into the
PHP code at the point they are called. It is not necessary that the filename extension of
the included file should have .php. We can use any extension we prefer for the files
included.

In the files depositdetails.php and loandetails.php we have placed the PHP code
inside the PHP tags. We have to do this if we want PHP code within a required file
treated as PHP code. If we did not open a PHP tag, the code will just be treated as text
or HTML and it will get printed as given. For example, lets modify
the loandetails.php as:
echo <h2>Loandetails<br> </h2>;

<?php

echo "<h4>Personal Loan Features & Benefits<br></h4>";

echo "You can Borrow up to Rs 20,00,000 for any purpose depending on your requirements.<br>";

echo "Repayment options, ranging from 10 to 60 months.<br>";

echo "If you are an bank salary account holder, we have a special offer for you";

?>

In this code we have written the echo "LoanDetails" outside the php tag. The output will
be printed as given.

Now when we execute the bank.php the output will be:

If your company has a consistent look and feel to pages on the website, you can use
PHP to add th e template and standard elements to pages using require() and include().
You can use this template in all pages, when you are making a minor change or
completely redesigning the look of the site, you need to make the change only in the
template file. You do not have to separately alter every page in the site.

If we have a set of function definitions in a script and want to use the functions in
another script then we can use include and require. Hence, once we write a function
definition in one file we can use that in N number of scripts . Hence any modifications
can be done in one file itself.

Difference Between Include and Require

include and require both work in the same manner, the only difference between them
is how they fail if the file cannot be found. The include construct will cause a warning to
be printed, but processing of the script will continue. Require , on the other hand, will
cause a fatal error if the file cannot be found.

For example;
<?php

echo "<h4>WELCOME TO STATE BANK<br></h4>";

require("depositdetails1.php");

echo "For net banking contact the <br>";

echo "corresponding bank where you have account";

?>

In the above code in require we have given a file name which does not exist. When we
run the bank.php script we get the output as follows:

Since the file does not exist, we get a fatal error and the execution stops there. Now
instead of require if we had used include we will get the output as:
In the above output we get only a warning, and so the rest of the statements in the script
get executed.

Include_once and Required_once

The include_once and required_once are similar to include and require, the difference
is PHP will check if the file has already been included, if so, it will not include it again. It
may be used in cases where the same file might be included and evaluated more than
once during a particular execution of a script. So in this case it may help avoid problems
such as function redefinitions, variable value reassignments, etc.

Note: include() , require() , include_once() , require_once() are built- in functions in PHP.

Built-in Functions in PHP


Every language has a set of built-in functions (for example, string functions see unit 2).
For example:
echo(PHP);
print(It is a server side programming language);

Some of the Array functions in PHP are:

1. array()
1. To Create an array
2. sort()
1. Sorts an array
3. array_unique()
1. Removes duplicate values from an array
4. count()
1. Counts no of elements in an array
5. array_reverse()
1. Returns an array in the reverse order

The above functions can be made use in scripts as follows;


<?php

$company=array("IBM","TCS","CTS","WIPRO","ACCENTURE");

for($i=0;$i
{

$sortedlist=array_reverse($company);

echo $sortedlist[$i]."<br>";

?>

Some of the character functions in PHP are:

ctype_upper()
Checks if all of the characters in the provided string are uppercase characters.
ctype_digit()
Checks if all of the characters in the provided string, text, are numerical.
ctype_alpha()
Checks if all of the characters in the provided string, text, are alphabetic.

There are also various other function categories that are not covered here.
Summary
Now that you have completed this unit, you should be able to:

Define functions to carry out specific tasks.


Invoke the function
Understand the scope of variables
Know how default arguments work
Describe some built-in functions in PHP
Identify various types of arguments

Problems to Solve
1. Write a function to generate the employee id. The function should generate the
2. employee id in a sequential manner.
3. Write a function to calculate the tax for an employee. To calculate the tax the user
4. should provide the salary amount and the function should return the tax amount.

Income % of tax
>180000 10

>400000 20

<180000 Nil

5. Write a function to reverse a string. Modification should be made in the original


6. string and temporary string variables should not be used.
7. Write a function to swap two string values using:
o call by value
o call by reference
8. Write a function to calculate the average for a student.

The user should provide marks for 5 subjects and the function should return the average.

Based on the average the grade is assigned. Also write another function to find the

grade. The user should receive only the grade as output.


Learning Objectives
At the end of this unit, you will be able to:

Understand what is an array


Know various ways to create ,access and modify the elements of an array
Understand how to iterate an array and modify the elements while iteration
Use various functions to sort an array
Create and manipulate multidimensional array

Introduction to Array
An array is a collection of related values stored under a common name.
Examples of an array could be list of items, marks scored in each level of a game or

monthly sales of a product

Array in PHP

An Array comprises of elements where each element is a key -value pair. For example

price of different ice cream flavors can be stored in an array as a key-value pair
Key has to be unique within an array. But Values can repeat. A particular ice cream flavor

can occur only once in the array. Almond Punch cannot be repeated in the array with

same/different price. But two different ice cream flavors can have the same price.

Therefore Almond Punch and Choco Dip can have the same price.

An array key has to be only a scalar value (String, Number, Boolean); whereas value of an

array can be both scalar (String, Number, Boolean) and non-scalar (array and other values).

PHP interpreter treats arrays with numeric keys and arrays with string keys (and arrays with

a mix of both) identically. Generally arrays with only numeric keys are referred as

"numeric," "indexed," or "ordere d" arrays, and with string-keyed as "associative" arrays.

In other words, an array whose keys are something other than the positions of the values

within the array is called an Associative array.

Creating an Array
Arrays can be created using

$arrayname [key]=value
$arrayname[]=value
array() language construct

Array creation using $arrayname [key]=value

To create the ice cream menu array


$icecream_menu['Almond Punch']=275; $icecream_menu['Nutty Crunch']=160;
$icecream_menu['Choco Dip']=290;
$icecream_menu['Oreo Cherry']=250;
To create an array with Numeric key
$icecream_menu[0]=275;
$icecream_menu[1]=160;
$icecream_menu[2]=290;
$icecream_menu[3]=250;

Arrays can be created with other scalar values as well as mix of them
$icecream_menu1[-1]=275;
$icecream_menu1[item 2]=160;
$icecream_menu1[3.4]=290;
$icecream_menu1[false]=250;

Creating array with [ ]

PHP automatically increments array key numbers when an array is created or add

s elements to an array with the empty brackets syntax


$items[]="pen";

$items[]="pencil";

$items[]='eraser';

echo $items[1]; //output: pencil

The empty brackets add an element to the array. The elements index/key will be

one more then the largest index available in the array at that time. If the array doesn't

exist yet, the empty brackets add an element with an index/key of 0.

Creating Array using array() construct

Arrays are generally created using array()


construct array([key =>] value, [key =>] value, ...)
The following creates an ice cream menu array
$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);

The Key is optional. When the Key is omitted, array is assigned a numeric key automatically

starting with index 0 from the first element onwards

The following creates an array with numeric index


$icecream_menu=array(275,160,290,250);

which is equivalent to the following array creation

$icecream_menu=array(0=>275,1=>160,2=>290,3=>250);

An array with a mix of all values can also be created


$icecream_menu=array(-1=>275,'item 2'=>160,3.4=>290,false=>250);

Creating an Empty Array

$marks=array();

The following assigns values to the mark array


$marks[0]=67;
$marks[1]=56.7;
$marks[]=89.5;

Accessing Elements of an Array

Array elements can be accessed using


$arrayname[key] format

For the array


$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);

To access the price of Choco Dip ice cream


print $icecream_menu['Choco Dip'];//output: 290

To access the element of the marks array


print $marks[1] ;// output:56.7

Modifying Elements of an Array


To Modify the price of Choco Dip ice cream
$icecream_menu['Choco Dip']=300;

Note: when attempting to modify, if an invalid key is given PHP will not throw an error.

Instead it will be considered as a new element

To modify the price of Choco Dip ice cream


icecream_menu[Choco dip']=300; //d is given in Lowercase instead of Uppercase

Since no such key called Choco dip is already available in the array, it is c onsidered as

a new element and added into the array

Therefore now the array contains 2 ice creams in the name Choco Dip and Choco dip
Finding the Size of an Array
The count() function is used to find the number of elements in the array
$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);
print "There are ".count($icecream_menu) ." flavours of icecreams available!!"

prints the following


There are 4 flavours of icecreams available!!

Printing an Array in a readable way

The print_r() ,when passed an array, prints its contents in a readable way.
$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);
print_r($icecream_menu);

Output of the above code will be


Array ( [Almond Punch] => 275 [Nutty Crunch] => 160 [Choco Dip] => 290 [Oreo Cherry] => 250 )

Iterating Array Elements

The easiest way to iterate through each element of an array is with foreach(). The

foreach()construct executes the block of code once for each element in an array.

Syntax

foreach($array as [$key =>] [&] $value)

//block of code to be executed for each iteration

$array represents the array to be iterated

$key is optional, and when specified, it contains the currently iterated array values key,

which can be any scalar value, depending on the keys type.

$value holds the array value, for the given $key value.

Using the & for the $value, indicates that any change made in the $value variable while

iteration will be reflected in the original array($array) also.

The following examples print the icecream flavours and its price in a table on the web

browser

<h3> align="center"><i&gtChillers...</i></h3>

<table align="center">
<tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>

<?php

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);

foreach($icecream_menu as $key=>$value)

print "<tr bgcolor='#F3F3F3'>"

print "&lttd>".$key."</td>&lttd>".$value."</td>";

print "</tr>";

?>

</table>

Output on the Web Browser

Modifying Array while iteration

Arrays can be modified during iteration in 2 ways.

Direct Array Modification


Indirect Array Modification

Direct Array Modification

Say for example we need to increase the price of the all icecreams by 50 .

The following code helps us to update the price and display the revised price along

with the old ones


<html>
<body>
<h3 align="center"><i>Chillers...</i></h3>
<table align="center">
<tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>
<?php

$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);

foreach($icecream_menu as $key=>$value)

print "<tr bgcolor='#F3F3F3'>";

print "<td>".$key."</td><td>".$value."</td>";

print "</tr>";

?>
</table>
<h3 align="center"><i>Chillers Revised Price.....</i></h3>
<table align="center">
<tr bgcolor="#D7D7D7" ><td >Icecream Flavours</td><td>Price</td></tr>
<?php

foreach($icecream_menu as $key=>&$value)

//increase the price of all icecreams by 50

$icecream_menu[$key]=$value+50;

$value=$icecream_menu[$key];

print "<tr bgcolor='#F3F3F3'>";

print "<td>".$key."</td><td>".$value."</td>";

print "</tr>";

?>
</table>
</body>
</html>
Indirect Array Modification

Recollect the foreach syntax


foreach($array as [$key =>] [&] $value) {

//block of code to be executed for each iteration

where '&'can be used with $value.Any change in $value,indirectly modifies the value of

the array for the current key during the iteration. The same output as above can be

achieved using the following code snippet


foreach($icecream_menu as $key=>&$value)

//increase the price of all icecreams by 50

$value=$value+50;

print "<tr bgcolor='#F3F3F3'>";

print "<td>".$key."</td><td>".$value."</td>";

print "</tr>";

Iterating Array with Numeric index


Arrays with numeric index can be accessed using

foreach()
for()
foreach() construct when used will give the value of the array, whereas for() construct

will give the position of the array element

The following example prints the hobby of a person using foreach() construct.

$hobbies=array("Reading Books","Playing Golf","Watching Tennis","Dancing");

print "<b>My Hobbies Are...</b>";

foreach($hobbies as $hobby)

print "<br> $hobby ";

The output of the following code on the Web Browser will be

My Hobbies Are...

Reading Books
Playing Golf
Watching Tennis
Dancing

Associative arrays can also be iterated using the foreach format shown above.

But the array key cannot be accessed. Only the array value can be accessed

The same output can be achieved using for() construct as follows

for($i=0,$arraysize=count($hobbies);$i<$arraysize;$i++)

print "<br> $hobbies[$i]";

Removing an element from an Array

The unset function is used to remove an element from the array


unset[$array[key]]

To remove Nutty Crunch from the icecream menu card


unset($icecream_menu['Nutty Crunch']);

The 'Nutty Crunch' element is removed from the array and the array size is
decremented by 1. Therefore there are only three flavours of ice cream instead of 4

Converting an Array to String

The implode() function is used to convert the array element into a string and to use

any delimiter if required between the array elements. The implode function in the

following example converts the hobbies array elements into a string by delimiting them

using a comma (,)


$hobbies=array("Reading Books,Playing Golf,Watching Tennis","Dancing");
$hobby="My Hobbies are ".implode(",",$hobbies);
echo $hobby;

Will display the output as


My Hobbies are Reading Books,Playing Golf,Watching Tennis,Dancing

Converting String to an Array


The explode function is used to convert a string into an array. The following code converts

games string into a favourite_games array by using explode();


$games="Golf,Cricket,Tennis,Football,Hockey";
$favourite_games=explode(",",$games);

echo "My second favorite game is ".$favourite_games[1];

displays the output as


My second favourite game is Cricket

Array Sorting
Functions that are used to sort an array in particular order are

sort()
asort()
ksort()
rsort()
arsort()
krsort()

sort() Function

Sorts the elements of an array in ascending order. The following code snippet sort the

games in ascending order


$games=array("Golf","Cricket","Tennis","Football","Hockey");
print("<b>Before Sorting.....</b>");

foreach($games as $game)

print "<BR>".$game;sort($games);

print "<br><br>";

print("<b>After Sorting.....</b>");

foreach($games as $game)

print "<BR>".$game;

Output of the above code in web browser is

Before Sorting.....

Golf
Cricket
Tennis
Football
Hockey

After Sorting.....

Cricket
Football
Golf
Hockey
Tennis

The sort() function should be used only for arrays with numeric index. When this function

is used on Associative array, the values are sorted in ascending order and the keys are

reset to numeric index.

The following code snippet sorts the icecream_menu array in ascending order of price.
$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);
print("<b>Before Sorting.....</b>");
foreach($icecream_menu as $flavour=> $price)
print "<BR>".$flavour." ".$price;
sort($icecream_menu);
print "<br><br>";
print("<b>After Sorting.....</b>");
foreach($icecream_menu as $flavour=>$price)
print "<BR>".$flavour." ".$price;

will display the output as


Before Sorting.....

Almond Punch 275


Nutty Crunch 160
Choco Dip 290
Oreo Cherry 250

After Sorting.....
0 160
1 250
2 275
3 290

The keys, which were strings before sorting, have been reset to numbers after sorting.

asort() function

The assort() function is used to sort an Associative Array in ascending order based on

its values. The keys are kept together with their values while sorting

The following code snippet sorts the icecream_menu array in ascending order of price.
$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);
print("<b>Before Sorting.....</b>");
foreach($icecream_menu as $flavour=> $price) print "<BR>".$flavour." ".$price;
asort($icecream_menu);
print "<br><br>";
print("<b>After Sorting.....</b>");
foreach($icecream_menu as $flavour=>$price)
print "<BR>".$flavour." ".$price;

will display the output as

Before Sorting.....

Almond Punch 275


Nutty Crunch 160
Choco Dip 290
Oreo Cherry 250

After Sorting.....

Nutty Crunch 160


Oreo Cherry 250
Almond Punch 275
Choco Dip 290

ksort() function

ksort() function is used to sort an associative array in ascending order based on their keys.
The values are kept together with their keys while sorting

The following code snippet sorts the icecream_menu based on its icecream flavours
$icecream_menu=array('Almond Punch'=>275,'Nutty Crunch'=>160,'Choco Dip'=>290,'Oreo Cherry'=>250);
print("<b>Before Sorting.....</b>");
foreach($icecream_menu as $flavour=> $price)
print "<BR>".$flavour." ".$price;
ksort($icecream_menu);
print "<br><br>";
print("<b>After Sorting.....</b>");
foreach($icecream_menu as $flavour=>$price)
print "<BR>".$flavour." ".$price;

will display the output as

Before Sorting.....

Almond Punch 275


Nutty Crunch 160
Choco Dip 290
Oreo Cherry 250

After Sorting.....
Almond Punch 275
Choco Dip 290
Nutty Crunch 160
Oreo Cherry 250
Reverse-Sorting functions

rsort()
arsort()
krsort().

Works similar to sort(), asort() and ksort() except that they sort the array in descending

order of values or keys depending on their nature.


Multi-dimensional arrays
Multi-dimensional arrays are arrays whose elements/values are arrays .In other words an

array within an array is called a multi-dimensional array

Instead of just icecream flavours and price, if each icecream flavour has a category

(single, family, couple, treat etc) based on which the price is decided ,it has to be

implemented using a multidimensional array


$icecream_menu=array('Almond Punch'=>array("single"=>275,"couple"=>425,"family"=>500),
'Nutty Crunch'=>array("couple"=>375,"family"=>450),
'Choco Dip'=>array("single"=>275,"Treat"=>425,"family"=>600),
'Oreo Cherry'=>array("single"=>450,"family"=>525));

Examples of some Multidimensional arrays would be

$favourite_games=array("indoor"=>array("Carom","Cards","Snook er"),"

out door"=>arr ay("Cricket","Football","Hoc key"));


$ordered_items=array(array("Ball otine of Salmon","Potage of Wild SeaBass" ,"Truffles"),

array("Poul et Bresse 'Cassoulet'", "Fillet of Venison","Monkfish Wrapped in Green Chilly,

Fillet of Aromatic Angus Steak"));

Accessing elements of a Multidimensional Array


echo "Almond Crunch, Couple Package Costs $".$icecream_menu['Almond
Punch']['couple']."<br>";
echo "My First Favourite Outdoor Game is
".$favourite_games['outdoor']['0']."<br>";
echo "The First Starter Dish Expected is ".$ordered_items[0][0]."<br>";

will display the output as

Almond Crunch, Couple Package Costs $425


My First Favourite Outdoor Game is Cricket
The First Starter Dish Expected is Ballotine of Salmon
Iterating Multidimensional Array
$favourite_games=array("indoor"=>array("Carom","Cards","Snooker"),"outdoor"=>
array("Cricket","Football","Hockey"));

The following code snippet iterates the favourite_games array


foreach($favourite_games as $category=>$games)

print("Favourite ".$category." games are ....<br></b>");

foreach($games as $game)

print $game."<br>";

The output will be displayed as follows


Favourite indoor games are ....
Carom
Cards
Snooker
Favourite outdoor games are ....
Cricket
Football
Hockey

Summary
Now that you have completed this unit, you should be able to

Understand what is an array


Know various ways to create ,access and modify the elements of an array
Understand how to iterate an array and modify the elements while iteration
Use various functions to sort an array
Create and manipulate multidimensional array

Problems to Solve
1. Write a function that accepts an array of numbers and sorts all even number first,
2. all odd numbers second in ascending order and then return the array
Example:
Input Array: 1,3,2,5,8,2,7,4,9,6,11
Output Array: 2,2,4,6,8,1,3,5,7,9,11
3. Create an array to hold 5 subject marks of a student. Calculate the grade and print
4. the grade of the student in the following format

Student Name:

Subject: Marks:

Maths 40

Science 60

English 90

Language 64

Moral Science 82

Total: Average: Grade:

The grade is calculated as follows:

o 90-100 O
o 70-89 A
o 60-69 B
o 50-59 C
o <50 F
o Write a function called sortArray() that Sorts the above array in the alphabetical

order of the subjects

o Modify Exercise 1 to create an array that hold 5 subject marks of 5 students

and calculate the grade and display as mentioned in Exercise 1.

o Create an array to maintain the population information of the country.

For every country the population count is given separately for male, female

and children in crs

India (50, 35, 23) Africa (67, 64.5, 60) Australia (20, 15, 10) China (100, 80, 85)

Iterate the array and print the Country names and their individual population count as

follows.

Country Male Female Children

The information should be displayed in the order of the country that has the highest

population
Learning Objectives
At the end of this unit, you will be able to

Understand the types of file manipulation in PHP.


List and make use of various functions that help to create, read and write disk files.
Know how to access information from the HTML page.

Introduction
Some applications require data to be available for several executions of the program, for
example, data on employees required by payroll applications. Data used in the programs
have a lifetime only till the duration of the program. They are stored in the RAM, and lose
their value once the program terminates. Unless explicitly placed in secondary storage
devices, the data kept in variables is lost once the program is terminated.

PHP offers a large set of functions for storing the data permanently into files, and to
perform manipulation like appending the data into a file, to delete the contents present in
the file etc.
File Open
Before performing any manipulation in the file, you should open it. Files are opened in
PHP using the fopen function. The function takes two parameters, the first is the name of
the file and the second is the mode in which it should be opened. The function returns a
file pointer if successful, otherwise zero.

Example:
$fp=fopen("Employeedetails.txt", "r");

Employeedetails.txt is the file which you are going to open and "r" denotes that the file
has been opened in read mode. If the file exits the function will return a file pointer else it
will return 0.

The following table shows the different modes the file can be opened in.
File Creation
Before you can do anything with a file it has to exist. In PHP the fopen function is used to
open files. However, it can also create a file if it does not find the file specified in the
function call. So if you use fopen on a file that does not exist, it will create it, given that
you open the file for writing or appending. For example:
$fp=fopen("Employeedetails.txt", "w");

In the above code you have opened the file in the write mode, so if Employeedetails.txt
file does not exist, it will create a file.

Note: The fopen function is used for opening and creating a file.
Writing to files
Now that you know how to open a file, let's get on to the most useful part of file
manipulation, writing. The fwrite function is used to write a string, or part of a string to a
file. The function takes three parameters, the file handle, the string to write, and the
number of bytes to write. If the number of bytes is omitted, the whole string is written to
the file. For example:
$fp=fopen("employeedetails.txt","w");
$name="john";
$id=123;
$address="Bangalore";
$salary=30000.56;
fwrite($fp,$name);
fwrite($fp,$id);
fwrite($fp,$address);
fwrite($fp,$salary);

The i$fp variable contains the file handle for employeedetails.txt. The file handle knows
the current file pointer, which for writing, starts out at the beginning of the file.
What happens when you open an existing file for writing? For example, if you want to
store another employee's details in the same file it can be written as:
$fp=fopen("employeedetails.txt","w");
$name="amit";
$id=124;
$address="Chennai";
$salary=30000.56;
fwrite($fp,$name);
fwrite($fp,$id);
fwrite($fp,$address);
fwrite($fp,$salary);

But here it will overwrite the previous contents, because you have opened the file in the
write mode. As mentioned earlier, in the write mode it opens and moves the file pointer to
the starting position, so the new content will overwrite the old one. If you read the
contents from the employeedetails.txt file only 'amit's' information will be available and
John's information will be lost. In this case you can open the file in the append mode,
where it will open the file and moves the file pointer to the end of file. You can modify the
above code as:
$fp=fopen("employeedetails.txt","a");
$name="amit";
$id=124;
$address="Chennai";
$salary=30000.56;fwrite($fp,"\r\n");
fwrite($fp,$name);
fwrite($fp,$id);
fwrite($fp,$address);
fwrite($fp,$salary);

Note: Windows requires a carriage return character as well as a new line character, so if
you're using Windows, terminate the string with \r\n.

If you want the lines to appear on separate lines in the file, use \n character. In the above
example to differentiate from one employee record with another one we have used \n.
The contents inside the employeedetails.txt will be
john123Bangalore30000.56
amit124Chennai35000

Reading from Files


Before we can read information from a file we have to use the function fopen to open the
file for reading. You can read from files opened in r, r+, w+, and a+ mode.
The fread function is used for getting data out of a file. The function requires a file pointer,
which we have, and an integer to tell the function how much data, in bytes, it is supposed
to read. Let us see an example to read the contents from the employeedetails.txt file.
$fp=fopen("employeedetails.txt","r");

$content=fread($fp,7);

echo $content;

The output of the above code will be john123, since we have given the number of
characters as 7. If you want to read all the data from the file, then you need to get the
size of the file. The filesize function is used to find the length of a file, in bytes; you need
to pass the filename as an argument to this function.
$fp=fopen("employeedetails.txt","r");

$content=fread($fp,filesize("employeedetails.txt"));

echo $content;

PHP also lets you read a line of data at a time from a file with the gets function. If you had
separated your data with new lines then you could read one segment of data at a time
with the gets function.
$fp=fopen("employeedetails.txt","r");

$content=fgets($fp);

echo $content;

For the above code you will get the output;


john123Bangalore30000.56

If you want to read all the lines from the employeedetails.txt file using fgets:
while(!(feof($fp)))

$content=fgets($fp);

echo $content;

In the above code we have used the feof function in a while loop, to read from the file
until the end of file is encountered. The feof function is used to determine if the end of file
is true. You can read a single character at a time from a file using the fgetc function:
while(!(feof($fp)))

$ch=fgetc($fp);

echo $ch;

Searching a record from a file

The Preg_Match PHP function is used to search a string, and return 1 or 0. If the search
was successful 1 will be returned, and if it was not found 0 will be returned. The syntax:
preg_match(search_pattern, your_string)

The search_pattern needs to be a regular expression.


If you want to search only amit's information from the employeedetails.txt file the following
code can be used.
$fp=fopen("employeedetails.txt","r");

while(!(feof($fp)))

$content=fgets($fp);

if (preg_match('/amit/',$content))

echo $content."<br>";

Closing a File
Once you have opened a file and finished your business with it is necessary to close that
file down. You don't want an open file running around on your server taking up resources
and causing mischief! The fclose() function is used to close an open file.
$fp=fopen("employeedetails.txt","r");
$content=fread($fp,filesize("employeedetails.txt"));
echo $content;
fclose($fp);

Some of the file manipulation functions in PHP:

rewind()
The rewind function is used to move the file pointer to the beginning of the file.
fputs()
The fputs() function is an alias of the fwrite() function.
fprintf()
The fprintf() function writes a formatted string to a file.
fscanf()
The fscanf() function parses the input from an open file according to the specified
format

Using PHP with HTML Forms


A very common application of PHP is to have an HTML form gather informat ion from a
website's visitor and then use PHP to process that information.
When a form is submitted to a PHP script, the information from that form is automatically
made available to the PHP script. Let's see an example of how to access information in
the PHP page

Customer.html

<html>
<body>
<form action="customer.php">
Name<input type="text" name="name"/><br />
Age<input type="text" name="age"/><br />
Gender:<input type="radio" name="gender" value="male"/> male
<input type="radio" name="gender" value="female"/> female <br />
Address <input type="text" name="address"/><br />
<input type="submit" value="save"/>
</form>
</body>
</html>

When you submit this form it will move on to the customer.php page. In this page we
need to access the information gathered in the customer.html file. Using $_GET and
$_POST variables you can access the information. Let us create the "customer.php" file
which will process the HTML form information.

Customer.php

<?php
$name=$_GET["name"];
$age=$_GET["age"];
$gender=$_GET["gender"];
$address=$_GET["address"];
echo "Name:".$name."<br>";
echo "Age:".$age.">br>";
echo "Gender:".$gender.">br>";
echo "Address:".$address;
?>

We have used the $_GET variable to collect form data & the names of the form fields
would automatically be the keys in the $_GET array.
The predefined $_GET and _$POST variables are used to collect values in a form with
method="get" and method="post". Since we have not specified any method name, by
default it would be GET.
Summary
Now that you have completed this unit, you should be able to:

Understand the types of file manipulation in PHP.


List and make use of various functions that help to create, read and write disk files.
Know how to access information from the HTML page.

Problems to Solve
1. Write a program to store the roll no, name, age, address, phone no of students into
the file called studentdetails.txt and the records should be stored in the format
given below
1. 101:priya:19:bangalore
2. 102:prem:20:chennai
3. 103:anu:18:chennai
4. 104:john:21:bangalore
5. 105:amit:20:Mumbai
2. Write a function to retrieve the student information from the studentdetails.txt file.
3. Write a program to display all the students who belong to the city bangalore from
the studentdetails.txt file.
4. Write a program to copy the contents of studentdetails.txt to
studentdetailsbackup.txt file.
5. Design a HTML page for getting the employee information such as name, age,
gender, qualification. Write a PHP script to access the employee information from
the HTML page and store it in a file employeeinfo.txt.

S-ar putea să vă placă și