web scripting with php 1-12

152
Es:iciriErcAr Table of Content 1. Introduction to PHP 1 2. Form Handling in PHP 13 3. Using Variables and Expressions in PHP 29 4. Using Variables and Expressions in PHP 41 5. PHP Operators 51 6. PHP Operators 63 7. Conditional Statements in PHP 75 8. Conditional Statements in PHP 89 9. Flow Control in PHP 105 10. Flow Control in PHP 115 11. Functions in PHP 123 12. Functions in PHP 139 13. Working with Arrays 153 14. Working with Arrays 167 15. Handling Databases with PHP 181 16. Working with Cookies 199 17. Working with Cookies 211 18. Session Management in PHP 221 19. Handling E-mail with PHP 239 20. Handling E-mail with PHP 247 21. OOP concepts 255 22. OOP concepts 267 Glossary i

Upload: mohaif

Post on 22-Oct-2014

180 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Web Scripting With PHP 1-12

Es:iciriErcAr

Table of Content

1. Introduction to PHP 1

2. Form Handling in PHP 13

3. Using Variables and Expressions in PHP 29

4. Using Variables and Expressions in PHP 41

5. PHP Operators 51

6. PHP Operators 63

7. Conditional Statements in PHP 75

8. Conditional Statements in PHP 89

9. Flow Control in PHP 105

10. Flow Control in PHP 115

11. Functions in PHP 123

12. Functions in PHP 139

13. Working with Arrays 153

14. Working with Arrays 167

15. Handling Databases with PHP 181

16. Working with Cookies 199

17. Working with Cookies 211

18. Session Management in PHP 221

19. Handling E-mail with PHP 239

20. Handling E-mail with PHP 247

21. OOP concepts 255

22. OOP concepts 267

Glossary i

Page 2: Web Scripting With PHP 1-12

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 2 of 274

bjectives

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

Discuss the history of PHP

Identify the need for PHP

Learn about PHP tools and setup

Write a simple PHP script

Learn about User 1/0

Use PHP to generate HTTP headers

Pass variables via URL

JILITody,ction

PHP stands for PHP - Hypertext Preprocessor. It is a scripting language used for developing dynamic Web pages. It is embedded within HTML codes. It is an open source Web page scripting language. PHP code is executed on the server and as a result the client cannot view the code.

In this session, we will learn about the history how to write a simple PHP script, how to generate HTTP headers using PHP and how to pass variables via URL.

1.114 61 Mo r Y.- of P

PHP is an advanced product of PHP/Fl. Rasmus Lerdorf created PHP/FI in the year 1995. PHP/ Fl stands for Personal Home Page/Forms Interpreter. Initially, it was a simple set of pert scripts, which was used for tracking accesses to his online resumes. These set of scripts were named as 'Personal Home Page Tools'. These scripts required more functionality. After writing larger C implementations, the scripts were able to work with the databases and the users were able to develop simple dynamic Web applications. In the year 1997, PHP/Fl got advanced to PHP/FI 2.0. Thousands of users had installed it in approximately 50,000 server domains. PHP/Fl 2.0 later got advanced to PHP 3.0.

PHP 3.0 is the first version of recent PHP. Andi Gutmann and Zeev Surakshi created PHP 3.0 in the year 1997. It provides a concrete infrastructure for different databases, protocols, and APIs to the end users. In addition, PHP 3.0"also provides object oriented syntax support. In the year 1998, PHP 3.0 got advanced to PHP 4.0.

PHP 4.0 includes supportive features for more Web servers, HTTP sessions, output buffering, and security while handling user inputs. This is the latest version of PHP.

Page 3: Web Scripting With PHP 1-12

Page 3 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Introduction to PHP

AprEcAf W 0-ft L'D W 1O E

PHP is used for server-side scripting. PHP is platform-independent. It can work on any operating system. The advantages of using PHP are:

It is easy to learn, use, and implement It is free for access

It can be executed on any platform

PHP is a scripting language and a set of tools. These tools are used for performing various server-side functions. In addition, it can also be used to execute scripts from the command line and for developing client-side GUI applications that can operate on any platform.

The following are some of the uses of PHP:

Application control - PHP was initially used as an application control language. It was designed to control access logging for HTTP servers. Later on, it was started being used as scripting language in applications, such as Microsoft Word and Excel.

Database Access - PHP is used with MySQL to access database. PHP can access any SQL or ODBC database. It can read and write data in the databases. Due to this feature, PHP is becoming famous for online business applications. As a. result, PHP has become a popular tool for e-commerce.

File Access - PHP is used to work with files. It can read and write files. It uses the documents for editing remotely. PHP is also used for generating files in various formats, such as PDF and HTML formats. It is a popular tool for HTTP distribution. It generates emails by taking data from the documents and sends it through any standard mail protocol. It has an ability to work with many data files and provide answer to the queries. As a result, it is an ideal tool for creating search engines and message boards.

Graphics - PHP can also manage graphical content. It can be used to create graphs and charts. It also generates image files such as GIF and PNG.

1.3 Introduction to PHP. tools and Setup.

PHP tools are used for developing and designing a Web page. These tools are the programming text editors. PHP tool contains all the supporting features for the fast development of Web sites. The tools that are used for developing dynamic Web pages under Linux environment are:

• PHPEd — Uses Linux platform as well as in Windows platform. It is available with version 3.3. It has an integrated development environment for PHP. It is freely available to the users. This tool helps in developing applications by supporting PHP scripts and its syntax.

Page 4: Web Scripting With PHP 1-12

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 4 of 27^

Session I EffPTECIff ORLDWIDE

Introduction to PHP

PHPDebugger DBG – Uses Linux as well as in Windows platform. Its current version is2.11.23. This tool is freely available to all. This tool helps the PHP scripts to execute in steps.It enables us to trace the errors in scripts.

ionCube Standalone PHP Encoder – Enables quick execution of scripts. It is freely available for Linux platform. Its updated version is 3.1.

Codelock – Uses Linux platform for working with PHP scripts. It is freely available with 2.0versions. PHing – Works on Linux platform. The tool depends on the platform where the PHP isworking. It is freely available for users. Its updated version is 1.0rc2. It performs various filesystem operations while processing a file.

NuSphere PHPEd – Uses 3.1.2 version on Linux platform. It is freely available to users. Itis an Integrated Development Environment that includes all functionalities for developingdynamic Web sites. This tool supports more than one application developers. xored:WebStudio – Uses the updated version of the tool. Its latest version is 0.2.2. It workson the Linux platform and is freely availability to the users. This tool is built on an eclipse platform. An eclipse platform is a tool platform for open source IDE.

PHPmole – Uses GNOME platform for working with PHP. GNOME platform is a desktopenvironment for Linux. The latest version of this tool is 1.3 and is freely available to the users. This tool is a combination of Dreamweaver software with Microsoft Visual studiosoftware.

Simplewire PHP SMS Software Development kit – Works on Linux platform. It is available in 2.3.0 version with freely available to users. This tools works with the wireless messaging network that enables us to send SMS to mobile phones.

Quanta Plus Web Development Environment – Uses 2.0 version of tool on Linux platform. It is freely available to the users. It is a Web development tool.

K PHP Develop – Works on Linux platform only. It is freely available with 0.1.6 version ofthe software. This tool supports MySQL as a database server. It has different modules, suchas server, server setup, clients, and plug-ins. It is an integrated Web development tool.

Gedit – Works on Linux platform. It is a text editor that is used for writing PHP scripts. Thistool does not have its own version because it comes by default when Linux is installed. Itis a normal text editor that is similar to notepad of Windows.

1.4 - Writino: a Simple Script

PHP file can include simple text, HTML codes, and PHP script. A PHP script starts with •?phptag and ends with the ?> tag. These scripts are embedded in the BODY tag of the HTML file- APHP file is saved with a p',lip extension.

Page 5: Web Scripting With PHP 1-12

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 5 of 27^

Session 1 rAJy7'ECAF

" - O R : L 0 W A 0 I E

Introduction to PHP

Some of the simple PHP scripts are:

To display current date using the PHP script:

1. Open the gedit text editor.

Enter the following code:

< HTML > <BODY> The Date is: <?php echo gmdate("M d Y");

</BODY> < /HTML.>

After entering the code, the text editor appears as shown in Figure 1.1.

Figure 1.1 Specifying Code

Note the PHP script is placed within the BODY tag of the HTML code. The text enclosedwithin <?php and ?> tag is sent to the PHP script engine for processing. After processingof the PHP script, the contents are returned to the browser as a normal Web page.

3. Save the file with the name, date.php under the /var/www/html directory.

5. Type http: / /localhost /date. php in the address bar and press the Enter key. The output appears, as shown in Figure 1.2.

Page 4 of 274 V 1.0 ©2004 Aptech Limited 5. Open the Mozilla Web b

Page 6: Web Scripting With PHP 1-12

APYIECH WORLDWIDE Session 1

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 6 of 27^

Introduction to PHP

Figure 1.2 : Displaying the Current Date

In the PHP script, echo command is used. The echo command displays contents in the Web browser. The gmdateo is a PHP function enables us to display current date and time in the browser. The gm stands for Greenwich Mean Time. This function displays the current Greenwich Mean Time date and time. The letter, M, used in gradate () function displays the month of the current date. The letter, M, displays only first three letters of the month. The letter, d, displays the current date and Y displays the current year. The letter, Y, displays all the four digits of the year.

To display simple text in the browser using the PHP script:

1. Open the gedit text editor.

2. Enter the following code:

<IITML> <BODY>

<?php echo "Hello Everybody";

</BODY> </HTML>

After entering the code, the text editor appears as shown in Figure 1.3.

o 'Ila z F i le Ed i t V iew Go Bookmark s Too ls w i ndow He lp

http:/Aocalhost/dat p_SearchBack Forward I E ___________ Reload Stop Print '!,1Home 1600kmark5 eRed Hat Network C, Support (,]I p (I~Products [T i i d

V illn ''X i

The Date is: Rin 22 2004

LS \Z, 0 (sR I Done

Page 7: Web Scripting With PHP 1-12

AP&I-EcArW 0 ft-LD W US.-E Session 1

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 7 of 27^

Introduction to PHP

v Un File Edit

V i e w

, __g r o ., N O

Search Tools Documents Help . .... .....

.

Find 11Save Print Undo Redo Cut Copy Paste

untitled i * x<HTML> <BODY> '<?php echo "Hello Everybody";

</BODY>

.. n .7, Col. 8 . ........ . .

INS

Figure 1.3 : Codes fordisplaying Text

Note the echo command is used to display the text. The text to be displayed is enclosed within double quotes.

3. Save the file with the name, stringdisp.php under the /var/www/html directory.

4. Open a Mozilla Web browser.

5. Type http: //localhost/stringdisp.php in the address bar and press the Enter key. The output appears, as shown in Figure 1.4.

Figure 1.4 : Displaying Text

"V 7, File Edit View Go Bookmarks Tools Window Help

http:lllocalhost/sti j*,SearchBack Forward Reload Stop __________________ 1-1

fa Home Xf Bookmarks elled Hat Network (:,,~Support (:Shop 67 Products (]6`rraining Hello Everybody

jk--- -- ---- --- 1-;D=, .. . ................. . ........ ......... L (32 Done

0

Page 8: Web Scripting With PHP 1-12

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 8 of 27^

In

(A—PrEciv~-R L!D W.1 D-E Sessi

Introduction to PHP

To display text in the Web browser with the help of a variable:

1. Open the gedit text editor.

2. Enter the following code:

<IITML> <BODY> The string j S

<?php $str = "My name is Samson"; echo $str;

</BODY> </HTML>

After entering the code, the text editor appears as shown in Figure 1.5.

% ' P U n t i t l e d

54we 406 R6d&4Cut Copy Paste Find r~ " Y N e w Open h t

l l n t i t l e d a i 4 s , ~ ~: .

<HTML> <BODY> <?php

echo $ s t r ;

</BODY> </HTML>

$ s t r = "My name i s Samson";

Ln 6, Col. 11 INS

Figure 1.5 : Using a Variable

In this example, the text is assigned to the variable named str. The second lineprovides the content of the variable str to the echo command. The echo commanddisplays the contents of str variable.

4. Open a Mozilla Web browser.

5. Type htt-p://I-ocalhost/stringname.php in the address bar and press the Enter key. The output appears, as shown in Figure 1.6.

3. Save the file with the name, stringname.php under the /var/www/htm] directory.

Page 9: Web Scripting With PHP 1-12

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 9 of 27^

Sess~on I

A ."L A) LWAOlz

Introduction to PHP

Figure 1.6 : Displaying the Content

Headers07"'N'7 to t e H I T V a d o r s

HyperText Transfer Protocol (HTTP) is a network transmission protocol that transfers hypertextfiles. It runs on top of TCP/IP suite, which is the foundation protocol suite for the Internet. HTTPprotocol includes three parts, such as the request and response line, the HTTP header, and thebody of the protocol.

HTTP header sends information to the client or the server about the application that wil l bedisplayed on the browser. The information about the application depends on whether the applicationis on request line or on the response line. HTTP header includes categories, such as:

General — Includes information about the client and the server

Entity — Includes information about the transferred data either from the client to the server or from the server to the client

Request or response — Includes information about the configuration of the client and theserver model. It also contains the information about the type of document the client isreceiving from the server and the document that the client will be sending to the

server_

InPHP, the header () function should be used to generate the HTTP headers. The header ()function sends the HTTP commands to the server through HTTP protocols. The scripts writtenin the header affects only the main display page. After the execution of header function, itdisplays a blank line showing that the header information is complete.

To use a simple header () function, the syntax is:

v o i d h e a d e r ( ' s t r i n g s t r i n g ' )

Page 10: Web Scripting With PHP 1-12

(A—PrEcK OAUDMUD-E Session 1

—77 — I —; f i x 77 File Edit view Go Bookmarks Tools Window Help . . .. ....... ....... .. . .. .... . ....... ......... .... 4 , Z ' ; ..... .. . ............. I : .

..- a- gname.phpn ,& http:jAocalhost/st6n *—Sea'ch ® R I Back Forward Reload Stop Print - ---- ------- I ---- ---- ------ -------

!

}

H

o

m

e

4

B

o

o

k

m

a

r

k

s

R

e

d

H

at

N

et

w

ork [ft

S

u

p

p

ort (

2j

S

h

o

V 1.0 2004 Aptech Limited Page 10 of 274

Introduction to PHP

Where,

string - Includes authenticating or validating strings for the server. The whole string is enclosed in the single quotes.

For example, use an authenticating string in the header ( function.

< ? p h p header('kNWVJ-Authenticate: Negotiate');

In the above example, WWW-Authenticate is a header that includes an authenticating parameter for the request made to the Web server. Here, Negotiate is one of the authenticating parameters.

Options such as replace and http_response_code can be used in a header () function along with the authenticating parameter.

1.5.1 replace Option

To use header () function with replace option, the syntax is:

void header ('string string', boolean replace)

Where, replace option replaces or adds header to the document.

The parameters of replace option shows whether the header needs to be replaced with a newheader or add a new header to the document. The header is normally replaced with a new header ifthere is no mention of any replace option. If the replace option is false then many newheaders will be added to the document.

For example, to add multiple headers to the document:

< ? p h p header('M%M-Authenticate: NTLM', false);

In the above example, false is the parameter of the replace option. NTLM is the authenticating parameter.

Page 11: Web Scripting With PHP 1-12

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 11 of 27^

Session 1 (A—PrEcff

0 R L D W : 1 0 Z

Option1.5.2 http–rcitponse, codeb-

To use header() function with http_response_code option, the syntax is:

void header (http—response_code)

Where, http—response—code shows the response of the Web server on any request, such as the status or the location of the client.

For example, to show the status of the client:

<?php header("HTTP/1.0 404 Not Found");

The above example shows the header string as HTTP/. The data in the rest of the string is the status of the client that was requested by the user.

For example, to show the location of the client:

<?php header("Location: http://www.msn.com"); exit;

The example shows the requested location on the browser. It also shows redirect status code ifthe redirect code is mentioned while displaying the status. In the above example, 404 is the statuscode used for displaying the status of the client.

Figure 1.7 shows the output of the above codes:

Figure 1.7 : Displaying the client location

Introduction to PHPWeb Scripting with PHP

V Elle Edit View Go Bookmarks Tools window . yelp

4, L*O http://www.msn.com/ H &%—Search L-4 .. Back Forward Reload stop Print . - -... . ........... Home 141 Bookmarks, t Red Hat Network (supportshop(dPfoducts (Training port

Netflix is your personal movie service. NO LATE FEES. Try FREE!

Search the Web'

AutosCareers & Jobs Dating & Personals Entertainment

T —d,, . Jo,?: Today On NNN

C—cr —sc: A -d.,

W — L d c — u o n t i [ c . Owl be a g) mi-k

I

.....ga 4 c»l G2 Done

Page 12: Web Scripting With PHP 1-12

APFECi, W 0 R L D W 1,0;5 Session 1

Page 12 of 274 V 1.0 © 2004 Aptech Limited

Introduction to PHP

PHP is a general purpose scripting language used for developing dynamic Web pages and is used with HTML coding scripts

PHP 4.0 includes supportive features for more Web servers, HTTP sessions, outputbuffering, security while handling user inputs, and many more new constructions forlanguages

PHP is developed from C-modules, therefore the scripts are also executed from the command line to make client-side GUI applications

PHP has become a popular tool for e-commerce because of its smooth accessibility to anySQL statements or any ODBC databases

PHP is also used for generating files in various formats, such as PDF and HTML formats. Itgenerates emails by taking data from the documents and sends it through any standardmail protocol

PHP is also used for generating graphical images, such as GIF and PNG images

A PHP script starts with <?php tag and ends up only with the ?> tag. These scripts are embedded in the HTML tags

A HTTP protocol is divided into three parts, such as the request and response line, the HTTP header, and the body of the protocol

PHP uses tools for developing and designing Web pages. These tools are the program text editors. Gedit is a popular text editor used for programming on Linux platform

SUMMARY

Page 13: Web Scripting With PHP 1-12

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 13 of 27^

Session 1 Introduction to PHP

1 PHP works in _______ language and uses tags within it.

a. HTML, FORM b. HTML, PHP c. scripting, HTML d. C, directive PHP is a user-friendly tool for making a. HTTP distribution b S h i

3. " The texts are displayed on the browser with the help -of - command.

a. echo b. GET C. d i sp lay d. PRINT

4. The contents from the database of the _________ are stored in _______

a_ Fields, browser b. Database server, forms C. Web server, variables d. PHP, variables

5_ PHP tool executes the scripts in step-by-step manner.

a. PHPEd b. PHPDebugger DBG C. Codelock

Phing

xored PHP tool works on the ___________ platform.

a. GNOME b. Linux C. Dreamweaver d. Eclipse

Page 14: Web Scripting With PHP 1-12

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 14 of 27^

Objectives

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

Use the GET method

Use the POST method

Retrieve data from forms using the Form methods

Use the hidden fields

J;,i.,itroductiom

PHP supports the powerful feature of handling forms. In PHP, we can retrieve the form data using the form methods such as GET or POST. The way data is retrieved depends on the method used for retrieving the data. PHP also enables us to pass the data from the hidden fields.

In this session, we will learn about the attributes of the form. We will also learn how to pass data from the form to the Web server using the GET and the POST method. In addition, we will learn how to retrieve data from the hidden fields in the form.

2 . 1 F o r m s :

A form provides a medium of interface for the client and the server to interact with each other. A form contains fields, where the user can enter information. This information is passed to the Web server for further processing. Forms are common on the Internet. A form appears on the display screen and the user fills in the information. This information is then passed to a form processing application that adds the information into a database.

PHP provides us with the powerful feature of handling forms. PHP provides built-in support for collecting data from a HTML form, where HTML stands for Hypertext Markup Language. The user enters the information in the HTML form. On submission of the form, the information is sent to the Web server, which in turn passes the information to the PHP script engine. The script engine then processes this information, manipulates it, and sends the output back to the Web browser.

A form consists of the following attributes:

Action - Specifies the Uniform Resource Locator (URL) that will process the form data and send the feedback. The URL- can be the URL of simple HTML page, PHP page, or any server-side script. The PHP script engine receives the information for processing when we specify the URL of the PHP page in the action attribute.

Method - Specifies the way the information is to be sent to the URL

Page 15: Web Scripting With PHP 1-12

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 15 of 27^

Form Handling in PHP

2.2 Using Methods

The Method attribute enables us to specify how data must be sent to the URL. It enables us tocontrol the process of data transfer to the Web server in the URL. There are two types ofmethods, GET and POST.

2.2.1 The GET Method

The GET method specifies the Web browser to send all the user information as part of the URL.In this method, a question mark is added at the end of the URL. This question mark indicates theending of the URL and the beginning of the form information. This information on the form istransmitted in the structure of name/value pairs to the URL.

The GET method passes the variables to the Web page by appending them at the end of the URL.

Consider the following example:

?Name=john

In the above example, Planets is the name of the field and earth is the value entered in the field. The question mark (?) symbol specifies to the browser that the element after it is a variable.

For example, this value will .be specified to the URL as follows:

http://www.lnformation.com/text.php?Name=john

The browser automatically appends the information to the URL when the page request is send to the server.

Multiple name/value pairs can be sent to the URL by separating each pair with the ampersand (&)sign. The name/value pairs are similar to variables. Once they are on the Web server for processing,PHP make them available as variables. The name/value pairs sent to the URL is a query string.

Consider the following example:

?Name=john&age=18

In the above example, the name/value pairs are by the ampersand (&) sign.

For example, this query string will be passed with the URL as follows:

http://www. Information.com/text.php?Name=john&age=18

The GET method is used to transfer limited amount of information.

2.2.2 The POST Method.:

The POST method specifies the Web browser that all the user information is sent through the body of the HTTP request. This method has the capacity to transmit more information through the

Page 16: Web Scripting With PHP 1-12

APY"C- C"WORLDWIDESession 2

Page 16 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Session 2 WORLDWIDE

Form Handling in PHP

body of the HTTP request. This is possible because there is no physical limit on the amount of information passed through the body of the HTTP

request_

Theinformation sent by the POST method is not encrypted. As a result, it is easily accessibleto a hacker. In order to secure the information, it is necessary to establish a secure serverconnection.

The POST method requests the server to accept the information in the body of the HTTP request.In the POST method, the variables are passed as they are passed in the GET method. Thedifference is that we cannot view the variables in the URL.

2.2.3 Difference in the GET and POST Method

The GET and POST methods work almost identically. The main difference is the way the informationis conveyed to the server. The GET method sends information through the URL whereas thePOST method sends information through the body of the HTTP request.

In GET method, there is less security because all the users are able to view the transmittedinformation in the URL. In the POST method, the information is not visible to all the users. Thishelps to provide security.

In the GET method, less amount of information is transmitted as compared to the POST method.

The GET method retrieves the information whereas the POST method manipulates the information on the Web server.

2.3 Retrieving Data .Using the GET Method

PHP uses variables to pass multiple data to a script- The way data is retrieved changes, depending on the method used to send the form data to the Web server.

The syntax to retrieve the data if we have used the GET method is:

$varname $_GET['variable'];

Where,

varname - Specifies the name of the variable in which the data is to be stored

S—GET['var fable' ]- Specifies the name of the input variable

For example, to retrieve the form data in the PHP script using the GET method: 1.

Open the gedit text editor.

Page 17: Web Scripting With PHP 1-12

(',6Vr,ECAF~17 0 R L. 0 W,1,0.8

Session 2

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 17 of 27^

Form Handling in PHP

2. Enter the following code to create a form that accepts the first and

phone number of the user: name, last name, address

<HTML> <BODY> <CENTER><BR><BR> <B>ENTER YOUR PERSONAL DETAILS</B> <FORM METHOD=GET ACTION="Detai1s.php"> FIRST NAME: <INPUT NAME="TEXT" TYPE="n1text"><BR><BR> LAST NAME: <INPUT NAME="TEXT" TYPE="n2text"><BR><BR> ADDRESS: <TEXTAREA NAME="n3text" ROWS=1, COLUMNS=1000></TEXTAREA><BR><BR> <BR> CONTACT NO.: <INPUT NAME="TEXT" TYPE="n4text"> <INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="SUBMIT"> <BR><CENTER> </BODY> </HTML>

After entering 'the code, the text editor appears as shown in Figure 2.1.

F i le Ed i t V i e w S e a r c h . . ' , . Tp d s D o c u m e n t s H e l p

ul n 9 New Open Save Pr in t Undo Redo Cut Copy Paste F ind Rep lace

Untitled 1* x

<HTML> <BODY> <CENTER><BR><BR> <B>ENTER YOUR PERSONAL DETAILS</B> <FORM METHOD=GET ACTION = 'Details.php'> <BR> FIRST NAME: <INPUT TYPE="TEXT" NAME="n1text"><BR><BR> LAST NAME: <INPUT TYPE="TEXT" NAME="n2text"><BR><BR> ADDRESS: <TEXTAREA NAME="n3text" ROWS=1 , COLUMNS=1000></TEXTAREA><BR><BR>I CONTACT NO.: <INPUT TYPE="TEXT" NAME="n4text"> <INPUT TYPE="SUBMIT" NAME "SUBMIT" VALUE="SUBMIT"> <BR></CENTER> </BODY> </HTML>

Ln 12, Col. 66 INS

Figure 2.1 : Creating the Personal Details Form

"n lrx,

Page 18: Web Scripting With PHP 1-12

AprEc" W 0 R L D W I'D E

Session 2

Page 18 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Form Handling in PHP

3. Save the file as Details.html under the /var/www/html directory.

4, Open a new file in the gedit text editor.

5. Enter the following code for retrieving the personal details:

<?php $A=$_GET['n1text]; $B=$—GET['n2Lext1; $C=$_GET['n3text]; $D=$—GET['n4text1; echo "YOUR PERSONAL DETAILS"; echo I/<BR><BR>"; echo "FIRST NAME: $A <BR>"; echo "LAST NAME: $B <BR>"; echo "ADDRESS: $C <BR>"; echo "CONTACT NO.: $D <BR>";

After entering the code, the text editor appears as shown in Figure 2.2.

f--. Untitled 1* x

<?php $A=$_GET['nitext']; $B=$_GET['n2text']; $C=$_GET['n3text']; $D=$_GET['n4text'];

echo "YOUR PERSONAL DETAILS"; echo "<BR><BR>"; echo "FIRST NAME: $A<BR>"; echo "LAST NAME: $B<BR>"; echo "ADDRESS: $C<BR>"; echo "CONTACT NO.: $D"; ?>I

Ln 12, Col. 3 INS

Figure 2.2 : Using the GET Method to Retrieve the Data

6. Save the file as Details. php,under the /var/www/html directory.

7. Open the Mozilla Web browser.

8. Type http-Hlocalhost/Details.htmi in the address bar and press the Enter key. The form to enter the personal details appears, as shown in Figure 2.3.

earchr",I.- Tgedit

r,:-% 1. . illA0 U I New Open Save Print Undo Redo Cut Copy . Paste Find Replace

Page 19: Web Scripting With PHP 1-12

Page 19 o f 274

APIIECH Session 2

A W 0'R L Ww' uo aV 1 . 0 C O

AForm Handling in PHP

X r F i l e E d i t V i e w G o B o o k m a r k s T o o l s W i n d o w H e l p

Search ] Y s hit 1 3411ocalhost/PersonalDet;t Back Forward Reload Stop Print

Home "Red Hat Network (:,jSupport g. Shop L~jProducts (ItTraining l ' IdBookmarks

ENTER YOUR PERSONAL DETAILS

FIRST NA.\.11-::

LAST NAME:

ADDRESS: I

co,N.-rAC'I- NO.: ISUBMIT

Figure 2.3 : Personal Details Form

9. * Enter John in the FIRST NAME text box.

10. Enter Simons in the LAST NAME text box.

11. Enter 32, Park Street, New Jersey in the ADDRESS text box.

12- Enter 45450 in the CONTACT NO. text box.

13. Click the SUBMIT button_ A page appears, as shown in Figure 2.4.

'IV IFfn 1!-X inn

Figure 2.4 : Displaying the Personal Details

Fi le Ed i t V ie w Go Book marks Too ls Win do w He l p C: :1 \3 -415, 14 http:/flocdvI

Back FoiWard Reload Stop L Search Print Home '4Bookmarks Red Hat Network (:,,ftsupport aft-.Shop ( 2 ~ (S

products iTrain

YOUR PERSONAL DETAILS

FIRST NAME: John LAST NAME: Simons ADDRESS: 32, Park Street, New- Jet---&!v CONTACT NO.: 45450

Done —[7

Page 20: Web Scripting With PHP 1-12

Session 2

('APrEcjv WOR4D W4 D E

Form Handling in PHP

P O S T 2.4;Retrieving: Data Using Met!lod

We can also use the POST method. The POST method sends data through the body of a HTTP request.

The syntax to retrieve the data if we have used the GET method is:

$varname = $_POSII'['variable'];

varname - Specifies the name of the variable in which the data is to be stored

$—POST[ 'variable' ] - Specifies the name of the input variable

For example, to retrieve the form data in the PHP script using the GET method:

1. Open the gedit text editor.

2. Enter the following code to create a form that accepts the employee details:

<HTML> <HEAD> <TITLE>Employee Details</TITLE> <FORM METHOD=GET ACTION="EMP_DETAILS.php" </HEAD> <BODY> <H4>Enter your details</H4> <FORM> <TABLE> <TR> <TD>Employee ID</TD> <TD><INPUT TYPE="text" NAME="empid"></TD> </TR> < T R > <TD>Name</TD> <TD><INPUT TYPE="text" NAME="name"></TD> </TR> < T R > <TD>Department</TD> <TD> <INPUT TYPE="radio" NAME--"dept" VALUE="Finance">Finance

<INPUT TYPE="radio" NAYIE="dept" VALUE="Marketiiig">Marke+,.,ing <INPUT TYPE="radio" NAME="dent" VALUE="TP">IT < /TD> </TR> <TP>

<TD>Einail</'1.'D>

Web Scripting with PHP V 1.0 © 2004 Aptech Limited

Page 21: Web Scripting With PHP 1-12

A, PVT IFCIN,

Session 2 Form Handling in PHP

<TD><INPIJ'T- TYPE="text" N.A11E="ernai 1 " >< /TD> </TR>.

</TABLE> <BR> <TD><INPUT TYPE="submit" VALUE="SUBMIT"></TD> </FORM> </BODY> </11TML>

After entering the- code, the text editor appears as shown in Figure 2.5.

jUntide4,'I-(Modiried).-.'gedit,. in X ,

i File . fdIt Mew search Tools L)ocurnents Help .. .. .......

New O p e n S a v e Pdnt' Undo R edo Cut Copy Paste Find Replace ... .. ........... . ........

L,,'Untitled 1• x <HTML> <11EAD> <TITLE>Employee Details</TITLE> <FORM METHOD=GET ACTION="EMP_DETAILS.php"</HEAD><BODY> <H4>Enter your details</H4> <FORM><TABLE><TR> <TD>Employee ID</TD> <TD><INPUT TYPE="text" NAME="empid"></TD></TR><TR> <TD>Name</TD> <TD><INPUT TYPE="text" NAME="name"></TD></TR><TR> <TD>Departnient</TD><TD> <INPUT TYPE="radio" NAME="dept" VALUE="Finance">Finance <INPUT TYPE="radio" NAME="dept" VALUE="Marketing"Aarketing <INPUT TYPE="radio" NAME="dept" VALUE="IT">IT</TD></TR> <TR><TD>Email</TD> <TD><INPUT TYPE="text" NAME="email"></TD></TR> </TABLE><BR> <TD><INPUT TYPE="submit" VALUE="SUBMIT"></TD>

1 </F0RM></B0DY></HTN1L>1

Ln 19, Col. 22 INS Figure 2.5 : Creating the Employee Details Form

3. Save the file as EMP_DETAILS.html under the /var/www/htmi directory.

4. Open a new file in the gedit text editor.

5. Enter the following code for accepting the values from the form: <?php <?Php $A= $—GET[ 'Crnpict' I $B=$_G-ET[ 'nzlule'] ; $C=$_GETj'deoL']; S " D =.

GET[ ' e ma i l ' ] ; echo "YOUR PERSONAL DETAILS"; e I I cirlo <BR><HR>";

Page 20 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Page 22: Web Scripting With PHP 1-12

Session 2 (A—Prircff

ORLDWIDE--1

Form Handling in PHP

e c h o " E M P I D : $ A < B R > " ; e cho "NA14E : $B <BR>"; e cho "DE PAR TMEN T NAME : $C <BR>"; e c h o " E M A I L : $ D <BR>";

After entering the code, the text editor appears as shown in Figure 2.6.

<?php $A=$-GET['empid']; $B=$-GET['narne']; $C=$-GET['dept']; S D = $ -GE T [ ' e m a i I ' ] ; echo "YOUR PERSONAL DETAILS"; echo "<BR><BR>"; echo "EMPLOYEE ID: $A<BR>"; echo "NAME: $B<BR>"; echo "DEPARTMENT NAME: $C<BR>"; e c h o " E M A I L : $ D " ;

AW A 6'0, xT

%I F i l e E d i t V i e w S e a r c h

Tools pocuments help

New Open Save Print Undo Redo Cut Copy Paste Find Replace

M -, Untitled 1* x

Figure 2.6 : Using the POST Method to Retrieve the Data

6, Save the file as EMP_DETAILS.php under the /var/www/html directory.

7. Open the Mozilla Web browser.

8. Type http-.Hlocalhost/EMP_DETAILS.html in the address bar and press the Enter key. The form appears, as shown in Figure 2.7.

~t~yee Details =:MOZilla -'

Figure 2.7 : Form for Accepting Employee Details

I Home IdBookmarks eRed Hat Network LAISUppott (:-!Shop (&roducts C6Traindrig

I-,- *a'-.D' G-r-

Employee ID

Name Dcpannmit Finwuc (- Marketing C IT Email

--------- -- ................. — ---------- __ 4 Done

File Edit View go Bookmarks Tools Window Help

t~ , a 3) hn,:Jji ih., DETA ;q Searchi Back Forward Reload Slop P i t

Enter your details

Web Script ing with PHP V 1.0 O c 2004 Aptech Limited Page 21 of 274

Page 23: Web Scripting With PHP 1-12

Session 2 Ef—EPTEC

ORL W I U I

9. Enter A05 in the Employee ID text box.

10. Enter Peter Taylor in the Name text box.

11. Select the department name as IT.

12. Enter [email protected] in the Email text box.

13. Click the SUBMIT button. -A page appears, as shown in Figure 2.8.

%0 Mortl[l1q :

Eile -~ * LAewGo Bookmarks Tools Wndow Lid P

http:/AocaJhostfEMP-DETA11j-1 ai,SearchBack Forward Reload —Stop- Print

_ILH=e I *Bookmarks j*-Red Hat Netmrk C`ySupport (6, ShOP Eftl`fOducts EtT raining

YOUR PERSONAL DETAILS

EMPLOYEE ID: A05 NAME: Peter Taylor DEPARTMENT NAME: IT EMAIL: [email protected]

~-~65'jl

Figure 2.8 : Displaying the Employee Details

2.-S. - 'Using : :Hidden Fields'

Sometimes we pass the information from one Web page to another without any interaction fromthe user. A hidden form field enables to pass information to the Web server. Hidden field is similarto the text field- The difference is that the user cannot view the hidden field and its contents. Toview whether the form contains the hidden field, the user needs to view the HTML source codeof the form.

The syntax to define the hidden filed is:

<INPUT TYPE=HIDDEN NAME=hiddenl VALUE="PHP MESSAGE">

Where,

INPUT TYPE - Specifies that the field is hidden Specifies the name of,the hidden field

> VALUE - Specifies the value as it appears on the form

In the above example, the form contains a hidden field containing the text, PHP MESSAGE.

Page 22 of 274 Form Handling in PHP

Page 24: Web Scripting With PHP 1-12

APTECK

Session 2 WORLDWIDE

For example, to use the hidden field and pass the name of the continents in the PHP script:

1. Open the gedit text editor.

2. Enter the following code to create a form that allows to select a continent:

<?php $var-l= "ASIA"; $var2 "AUSTRALIA"; $vaj--3= "EUROPE"; echo '<FORM METHOD='GET' ACTION='Display php'>; echo " Specify the continent?"; echo "<SELECT TYPE='LISTBOX'' NAME='continent'>; echo "<OPTION>$varl</OPTION>"; echo "<OPTION>$var2</OPTION>"; echo "<OPTION>$var3</OPTION>"; echo "</SELECT><BR><BR>"; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN1 VALUE='$var1'>; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN2 VALUE='$var2'>; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN3 VALUE='$var3'>; echo "<INPUT TYPE=SUBMIT>";

echo. "</FORM>";

After entering the code, the text editor appears as shown in Figure 2.9.

Figure 2.9 Creating a Form with Hidden Fields

3. Save the file as Continent.php under the /var/www/html directory.

V Untitled Llk,

F i l e Ed i t V iew Search Too ls L)ocurnen ts He lp .. . .........

40, E4 ID It n

New Open Save Pr int Undo Redo Cut Copy Paste Find Replace

Untitled 14 x

<?php Svarl="ASIA"; $var2="AUSTR4,IA"; $var3="EUROPE",- echo "<FORM MFTHOD='G2T' ACTION= 'Display.plip'>"; echo " Specify the continent?"; echo "<SELECT TYPE='LISTBOX' NAME='continent'>"; echo "<OPTION>$var1</OPTION>"; echo "<OPTION>$var2</OPTION>"; echo "<OPTION>$var3</OPTION>"; echo "</SELECT><BR><BR>"; echo "<INPUT TYPE=HIDDEN NAME=HIDDEN1 VALUE='$varl'>";echo "<INPUT TYPE=HIDDEN NAME=HIDDEN2 VALUE='Svar2 I > .1 ;

echo "<INPUT TYPE=HIDDEN NAME=HIDDEN3 VALUE='$var3'>";echo "<INPUT TYPE=SUBMIT>"; echo "</FORM>";

Web Scripting with PHP V 1.0 C 200 Aptech Limited

Page 25: Web Scripting With PHP 1-12

APTHCH,

Session 2 WID R

Form Handling in PHP

4. Open a new file in the gedit text editor.

S. Enter the following code for retrieving the options selected by the user:

<?php $A=$_GET['HIDDEN1']; $B=$_GET['F1IDDEN2'11- $C=$_GET['HIDDEN3'1; $name=$_GET['continent'1; echo ("Continents<BR>"); echo '<BR>"; echo $A; echo "<BR>"; echo $B; echo "<BR>"; echo "$C echo "<BR>"; echo "<BR>The continent you have selected is:<BR>; echo "$name";

After entering the code, the text editor appears as shown in Figure 2.10.

Figure 2.10 : Retrieving the Data from Hidden Fields

6. Save the file as Display.php under the /var/www/html directory.

7. Open the Mozilla Web browser.

! j n l q d t 4 f l e o t 9 e f I (%q4L ~iL I File Echt View Search Tools Qocumerds

- -- - ----------_- . .... ....

New Open Save Print Undo Redo Cut Copy, Paste Find Replace

Untitled 1*

<?php $A=$_GET['HIDDEN1'1; $B=S_GET['HIDDEN2'1; $C=$_GET['HIDDEN3'1; $name=$_GET[ 'continent') echo ("Continents<BR>"); echo " <BR> echo $A; echo " <BR> echo $B; echo "<BR>"; echo $C; echo "<BR>The continent you have selected is:<BR>"; echo "$name";

Ln 15, Col. 3 INS

i

Page 24 of 274 V 1.0 Oc 2004 Aptech Limited Web Scripting with PHP

Page 26: Web Scripting With PHP 1-12

Session 2

E4lt_s_-72rECAIT L;V W 1'D E

8. Type http://Iocalhost/Continent.php in the address bar and press the Enter key. The continents form appears, as shown in Figure 2.11.

File Edit: View Go' Bookmarks Tools Wridaw Help

http:j/l, v . 0 , Search Back Forward Reload StopPrint

1

Home Vj Book marks **- Red Hat Network [Support A Products QftTr~

Submit Query

Specify the continend ASIA

EM c3`3

Figure 2.11 : Continents Form

9. Select Europe from the Continent drop-down menu.

10. Click the Submit Query button. The page appears, as shown in Figure 2.12.

Form Handling in PHP -M z1l1a.'.'..' n I*

File Edit View Go Bookmarks Tools Window Help L Search El

Back Forward Reload Stop Ltti~/'E Print . . ............... ............ ~,j Home Xf Bookmarks -**Red Hat Network LjSupport [Shop L-1 Products Ljtj, Continents

AS IA AUSTRALIA EUROPE

The continent you have selected is: EUROPE

M14 Bone ............. ....

Figure 2.12 : Displaying the Selected Continent

Web Scripting with PHP V 1.0 ©2004 Aptech Limited Page 25 of 274

Page 27: Web Scripting With PHP 1-12

Session 2 (A—PrEcm~+L:DWID.N

Form Handling in PHP

,,SUMMAR);> A form provides a medium of interaction where users can fill in data.

PHP has a built-in support for collecting data from a HTML form.

The information from this form is automatically available to the script engine. The script engine then process the information.

When the server accepts a form it recognizes the form as a collection of codes.

The attributes of a form as are as follows:

Action: Specifies the Uniform Resource Locator (URL) that will process the form data and send the feedback

Method: Specifies the way the information is to be sent to the URL

The GET method specifies the browser to send the values the user placed on the form to the URL. The URL is the Uniform Resource Locator.

The POST method informs the browser to send the values the user placed on the form to the PHP script engine in the body of the HTTP request.

Hidden form fields enables form developers to pass information, from a form to a script, or from one form to another, before being passed to a script.

Hidden form fields are not visible to users.

Page 26 of 274

Page 28: Web Scripting With PHP 1-12

Session 2

(A—PTEC-V W O R L D W I D E &

Form Handling in PHP

1 provides an interaction between client and the server.

a. Action attribute

b. Methods

C. Form

2. HTML stands for __________

a. Hyper Text Mode Language

b. Hyper Text Markup Language

C. Hyper Text Manual Language

3. The ___________ specifies the Uniform Resource Locator (URL) that will process the form data and send the feedback.

a. Method

b. Form control

C. Action attribute

4. is an application program that performs the task of understanding the form, and interpreting it to the server.

a. URL

b. PHP

C. HTTP

d. None of the above

5. In the GET method, ___________ is added at the end of the URL.

a. ?

b. / C.

..............

V 1 . 0 O c 2 0 0 4 A p t e c h L i m i t e d Page 27 of 27zl

Web Scripting with PHP

Page 29: Web Scripting With PHP 1-12

Session 2 (A—OR LD, EW 10.0-EY

Form Handling in PHP

method sends the information in the body of the HTTP request.

a. POST

b. GET

C. BODY

d. None of the above

Page 28 of 274 V 1.0 (D 2004 Aptech Limited Web Scripting with PHP

Page 30: Web Scripting With PHP 1-12

0 bjectives

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

Define Identifiers

Lists the data types

Use variables and constants

Define the scope of variables

Use the HTTP environment variables

4ntroduction

In programming, we use variables. A variable stores the data that keeps on changing. Different types of data can be stored in a variable. An expression consists of variables and operators.

In this session, we will learn about the identifiers, data types, variables, constants, and expressions. In addition, we will learn about the scope of variables and HTTP environment variables.

3.1 identifiers.

Identifiers are names given to various elements of a program such as variables, constants, arrays, and classes in a program. We must keep some points in mind while naming an identifier. They are:

• An identifier must begin with a letter • It must contain only letters(A to Z) or digits(0-9) • We can use underscore(—) to add space in the identifier to make it more readable

An identifier must not include any special characters including blank space

Some of the valid identifiers are firstnum, ]name, net—sal, add8num, and NewNum.

Some examples of the invalid identifiers are shown in the Table 3.1.

Identifier Invalid Because

f irst.-num Use othyphen not allowed

l n u m First character cannot be a number first num Use of blank space not allowed I . J . r s t & num Use of ampersand not allowed

Table 3.1 : Invalid Identifiers

Web Scripting with PHP V 1.0 © 2004 Aptech Limited Page 29 of 274

Page 31: Web Scripting With PHP 1-12

Session WORLDWIDE

Using Variables and Expressions in PHP

3.2 Variables and Data Types.

A variable is an identifier whose value keeps changing. A variable has a name and a data type. The name refers to the value in the variable and the data type refers to the type of data the variable can store. We use variables to store user information, intermediate data such as calculated results, and values returned by the functions.

Variables are used to store a data value in it. Variable data type means the type of data the variable can hold. Table 3.2 shows the data types of PHP:

Table 3 .2 : Data Types

In PHP, do not need to declare a variable. A variable is automatically declared at the time of initializing the variable. The variable is declared with the data type as that of the value stored in the variable. As the value of the variable keeps on changing, the data type of the variable also keeps on changing.

A dollar ($) symbol must be placed before a variable name. This symbol helps to differentiate a variable from other statements in the code. Variables are case sensitive. For example, a variable name, $var–name-, is different from a variable name, $Var–Name.

If a variable is created without any value assigned to it, its takes the value as NULL. The data type of such variable will automatically change during the execution time.

The syntax to initialize a variable is:

$ v a r i a b l e _ n a m e = v a l u e ;

Page 30 of 274

Page 32: Web Scripting With PHP 1-12

Session 3 64—PTIECII

Using Variables and Expressions in PHP

Where, $variable name - Specifies the name of the variable

• value - Specifies the value the variable will store

V 1.0 C 2004 Aptech Limited RLDWIDE

When we assign a value to a variable, we are performing an assignment operation- An assignmentoperation is performed with the help of an equal to (=) sign that is placed between the variableand the value. The equal to (=) sign is called the assignment operator. The left side of theassignment operator has the name of the variable and the right side of the assignment operatorhas the value for the variable. The name on the left side of the assignment operator can be thename of a constant or a variable. A value of an expression can also be assigned to a variable.An expression consists of variables and operators. Some of the examples for the variables are:

To store the integer in the variable:

$ S a l a r y = 5 0 0 0 ;

Note the $Salary variable will be declared as the numeric variable because the value assigned to it is of the integer data type.

To s tore st r ing in the var iab le : $message

= "HELLO! How are you?"

Note the $message variable will be declared as the string variable because the value assigned to it is of the string data type. The string is enclosed within the double quotes.

To store the value of an expression in the variable: <?php

Web Scripting with PHP

Page 33: Web Scripting With PHP 1-12

Session 3 (A—PrEc'--f1\!_oe L D WA Z:e

Using Variables and Expressions in PHP

The syntax to assign a value to a variable using the reference of another variable is:

$new_varname =& $old–varname

Where,

$new – varname – Specifies the new variable name );> " $old_varname – Specifies the old variable name

For example, to assign a value of one variable to another:

<?php $Fname = "John"; $Lname = "Smith"; $name =& $Fname; echo $name;

echo $Lname;

Note the variables, $Fname and $Lname are string variables. The reference of the $Fname variable is given to the $name variable with the help of an equal to and ampersand symbols.

3.3 Constants

Constants are identifiers that contain values that do not change as the program executes. Likevariables, constants are also case-sensitive. Once a constant is defined, it cannot be changed.A constant is declared using the define ( ) function. A constant has a global scope of existence. Itcan be accessed from anywhere in the script regardless of its position in the script.

The syntax to declare a constant using the define () function is:

define(string_name, mixed value

Where,

string_name – Specifies the variable name for the constant mixed value– Specifies a numeric or string value that is to be made constant

For example, to declare the constant, NAME, containing a string value:

<?php define("NAME", "John Smith"); echo NAME; echo name;

Page 32 of 274 V 1.0 ©2004 Aptech Limited Web Scripting with PHP

1

Page 34: Web Scripting With PHP 1-12

S e s s i o n 3

( A k 0 T, ECH:0~ 0 R L D-WTD-E

Using Variables and Express ions in PHP

In the above code snippet, a constant is declared. On executing the statement, echo NAME, the string value stored in the constant will be displayed. But, on executing the statement, echo name, an error message will be displayed. This is because constants are case-sensitive.

We can also declare constants that are not case-sensitive using the defineo function. The syntax to create constant that case-insensitive:

define(string_name, mixed value, case insensitive

Where, case–insensitive specifies a Boolean value, TRUE or FALSE. If the value specified is TRUE, the constant name will be case insensitive

different cases represent : different . values . in

Two constants with the same 'name

For example, to declare a constant that is case insensitive:

<?php define("NAME", "Michael Graff", TRUE); echo NAME; echo name;

Note the TRUE value in the defineo function indicates that the constant to be declared mustbe case-insensitive. Now on executing both the statements, echo NAME and echo name, the string value stored in the constant will be displayed.

t.4 Scope. of Variables

The scope of a variable is the portion in.the script within which the variable is defined. The scope of a variable indicates the lifetime of a variable- The lifetime of a variable is the duration from the time the variable is created to the time the execution of the scripts ends. In PHP, the following arethe different scopes of variables:

> Local > Global > Static

AMA Local 'Variables

Web Scripting with PHP A v a r i a b l e i n i t i a l i z e d

Page 35: Web Scripting With PHP 1-12

A P T E C ' F " r ,

Sess6on 3 W-0,91L.W.W.VDa

Using Variables and Expressions in PHP

For example, to display product of two numbers-.

<?php echo "a'he multiplication value of 14 15 function multiply()

$num1=14; $num2=15; $num2=$numl $num2; echo $num2;

multiply();

In the above code snippet, the variables, numl and num2 are declared inside the function as the local variables of the function. They are initialized and used inside the multiply ( ) function. The product of two variables, numl and num2 is calculated in the multiply() function. This function executes when the PHP script calls the function using the function name.

0.4.2 Global Variables When a variable retains its value throughout the lifetime of the web page, it is called the globalvariable. The global variable is declared with the help of the keyword global within the function. As a result, it can be accessed from any part of the program.

The syntax to declare a global variable in a program is:

global $var_name;

Where, $var_name specifies the variable name that needs to be made global. For

example, to perform multiplication of two numbers using the global variables:

<?ph-o

$varl = 4; $var2 = 15;

function multiply()

global $varl, $var2; Svar2 = $varl * $var2; echo $var2;

echo "The multiplication value of 4 * 1.5 multiply();

Page 34 of 274 V 1.0 C 2004 Aptech Limited Web Scripting with PHP

Page 36: Web Scripting With PHP 1-12

~A_PiEclff

Session 3 W-O.R L D W I D E

Using Variables and Expressions in PHP

In the above code snippet, the variables, varl and var2 are declared as the global variables.They are initialized outside the function and declared as global within the multiply ( ) function.The product of two variables, varl and var2 is calculated in the multiply() function. Thisfunction executes when the PHP script calls the function using the function name.

3A.3 Static V i bl

A static variable is similar to a local variable. The only difference is that the static variable retainsits value even after the function terminates. When a function terminates, the values of the localvariables of that function looses its values. To retain the value of the variable throughout theexecution, use the STATic keyword with the variable name. The static variable is used in therecursive function. A recursive function calls itself recursively within a function.

The syntax to declare a static variable is:

static $var_name = value;

Where,

);,. var_name — Specifies the variable name value — Specifies the value of the variable

For example, to use the static variable in a function: <?php function sum()

static $varl = 9; $varl=$varl + 12; echo $varl;

echo "The addition value of 9 + 12 sum

In the above code snippet, the varl is declared as the static var iable. It is declared inside thesum ( ) function. The variable varl is local to the sum( ) function but it retains its value throughout theprogram.

3.5 HTTP Environment Variables

Environment variables are system-defined variables that we can use in any PHP script. Thesevariables provide information about the transactions held between the client and the server. Theyprovide information about the HTTP request or the HTTP response. The environment variables aresimilar to the user-defined variables because they also begin with the dollar ($) sign.

Web Scripting withi PHP V 1.0 (0) 2004 Aptech Limited Page 35 of 274

Page 37: Web Scripting With PHP 1-12

Session 3Using Variables and Expressions in PHP

Some of the environment variables are:

SERVER_-SOFTWARE – Returns the name and the version of the server software. To view the server software and its version, enter the following PHP script:

<?PHP echo $HTTP_SERVER–SOFTWARE;

SERVER–NAME – Returns the server hostname. The hostname can be the IP address or the DNS name of the server. To view the server name, enter the following PHP script:

<?php

echo $HTTP_SERVER NAME;

SERVER–PROTOCOL – Returns the name and version number of the protocol that called the script. To view the server protocol, enter the following PHP script:

<?php echo $HTTP_SERVER_PROTOCOL;

SERVER–PORT – Returns the port number for the script. To view the server port, enter the following PHP script:

<?php echo $HTTP–SERVER–PORT;

COOKIE_-DATA – Returns the content of the recently used cookie. A cookie stores userinformation sent to the browser by the Web server. A cookie is saved as a text file. A cookieis sent back to the server when the browser requests to display a page. To view the cookiedata, enter the following PHP script:

<?php echo $HTTP_C00K1E_DATA;

POST–FILES – Returns information about the uploaded files. To view the uploaded files, enter the following PHP script:

<?php echo $11TT11–POST–FILES;

Page 36 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Page 38: Web Scripting With PHP 1-12

AprEcAel

Session 3 W 0 R L'D;WI 0,6

Using Variables and Expressions in PHP

MTPUSER–AGENT – Returns the name of the browser the client is using. To view the type of the browser, enter the following PHP script: <?php echo $HTTP_USER_AGENT;

HTTPACCEPT – Returns a list of media types the client will accept. To view the list of media types, enter the following PHP script:

<?php echo $IITTP_ACCEP,r;

HTTP_FROM – Returns the e-mail address of the users those who have made any request to the server. To view the email addresses of the users, enter the following PHP script:

<?php echo $HTTPFROM;

Web Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 37 of 274

Page 39: Web Scripting With PHP 1-12

Session 3 F.= CH

DR-L.11 W I - D a

Using Variables and Expressions in PHP

SUMMARY

Identifiers are names given to various elements of a program such as variables, constants, arrays, and classes in a program

A variable is an identifier whose value keeps changing. Variables are used to store a data value in it

A dollar ($) symbol must be placed before a variable name Constants are identifiers that contain values that do not change as the program executes

A constant is declared using the define() function

The scope of a variable is the portion in the script within which the variable is defined. The different scopes of variables are local, global, and static

A variable initialized and used inside a function is called a local variable When a variable retains its value throughout the lifetime of the web page, it is called the global variable. It is declared with the help of the keyword global within the function

The static variable retains its value even after the function terminates- It is declared with the help of the keyword static with the variable name

Environment variables are system-defined variables that we can use in any PHP script Environment variables provide information about the HTTP request or the HTTP response A

COOKIE–DATA environment variable returns the content of the recently used cookie

)> The environment variables are similar to the user-defined variables because they also begin with the dollar ($) sign

Page 38 of 274

Page 40: Web Scripting With PHP 1-12

A P MCM

Session 3 WOM-LDWIDE

Using Variables and Express ions in PHP

CHECK YOUR 1. An assignment operation is performed with the help of _________ sign.

a.

2- A constant is declared using the _______________ function.

a. constant()

b. define()

C. string

3. A constant has _________ scope of existence.

a. Local

b. Static

C. Global

4. The _________ environment variable returns the content of the recently used cookie.

a. SERVER—SOFTWARE

b. SERVER_PORT

C. COOKIE__DATA

d . H T T P _ A C C E P T

5. The __________ environment variable returns the name and version number of the

protocol.

a. SERVER—PROTOCOL

b . SERVER_PORT

C . H T T P _ P O S T d .

H T T P _ F R O M 11

Web Scripting with PHP V 1.0 (6 2004 Aptech. Limited Page 39 of 274

Page 41: Web Scripting With PHP 1-12

A1072FCIN

Session 3 W0.K--L,DW 'Or=

Using Variables and Expressions in PHP

6. The data type stores true or false values.

a. string

b. integer

C. floating-point

d. boolean

7. The ________________ variable retains its value through out the lifetime of the program.

a. local

b. static

C. global

d. environment

8. The ______________ environment variables returns information about the uploaded files.

a. SERVER—PROTOCOL

b. SERVER—NAME C. POST—FILES

d. SERVER—PORT

_ _— 40 of 274 V 1.0 @ 2004 Aptech Limited Web Scripting with PHP

Page 42: Web Scripting With PHP 1-12

Objectives

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

Use the assignment operator

Use local variables

Use global variables

Use static variables

The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully.

Part I - For the first 1.5 Hours:

4.1 Using the Assignment Operator

A variable is an identifier whose value keeps changing. A variable has a name and a data type. The name refers to the value in the variable and the data type refers to the type of data the variable can store. We use variables to store user information, intermediate data such as calculated results, and values returned by the functions_

Whenwe assign a value to a variable, we are performing an assignment operation. An assignment operation is performed with the help of an equal to (=) sign that is placed between the variable and the value. The equal to (=) sign is called the assignment operator. The left side of the assignment operator has the name of the variable and the right side of the assignment operator has the value for the variable. The name on the left side of the assignment operator can be the .name of a constant or a variable. A value of an expression can also be assigned to a variable.

Open the gedit text editor.

To assign a string value to a variable and display it, enter the following code:

<HTML> <HEAD>

<TITLE>String Assignment Operation</TITLE> </HEAD>

<BODY>

<?php

3

Web Scripting with PHP V 1.0 (P 2004 Aptech Limited Page 41 of 27s'~'

Page 43: Web Scripting With PHP 1-12

S e s s i o n 4 (A"PrEcmW" WORLDWIDE

Using Variables and Expressions in PHP

ave,the,file as r.php under the /y directory. directr .y

yp.6 ust :r -in the address barand:pressAhe,,Enter~'

X4 iloci l lib e t l a ggg php

Bookmarks Red Hat Network

This is John Ci77el

Figure 4.1 : Displaying a Str ing

Open a new file in the text editor.

To calculate the product of two numbers and assign it to a variable, enter the following code:

<HTML> <HEAD> <TITLE>Integer Assignment Operation</TITLE> </HEAD>

<BODY>

Page 42 of 274 V 1.0 (-c,) 2004 Aptech Limited Web Scripting with PHP

Page 44: Web Scripting With PHP 1-12

Session 4

~P~̀EaC'/Si

Using Variables and Expressions in PHP

$int -valuel = 13; $ i n t value2 = 451 W i t valu462 ..•'$int---valuel $int~_value2; $int va $iift_vdIde2,~e c h o $int-yal d2y

</BODY> </HTML> S -the file as.aftighlilt.ph

,Open the Mozilla aVd,

b%46Wi

Integer Assignment Operation - Mozilla

tl*Back

!,Home I IdBookmarks eRed Hat Network GAsupport rA~Shop L_jproducts L4Tralrflng

The product of 13 - 45 = 585

I --------

L.'%, L . 4,' 93 42 j Done Figure 4.2 : Displaying the Value of an Expression

4

.11. Open a new file in thd~ltext editor.

12. To subtract a decimal number from another and assign its value to a variable, enter the following code:

<HTbiL> <HEAD> <TITLE>Float Assignment Operation</TITLE> </HEAD>

Web Scripting with PHP V 1.0 (L',, 2004 Aptech Limited

Page 45: Web Scripting With PHP 1-12

S e s s i o n 4 W a IRI*Llo W.1 D.E.

Using Variables and Expressions in PHP

The output appears, as shown in Figure 4.3.

<BODY>

float--Yaluel. = 134.57;.; fleet vAlliez = 12.87;float value2, = $float_valuel L6:~ "The subtraction value of - 4rjLoat vajue2;:

` v LFf0atAA1gj r t t iowe. o r t l l a 11n i 'XFile Edit View Go Jiookmatks Tools Window Help ............. . .. . ...... .. ......

Imm3 ' http:/Aocalhost/assignflo L -j[;_; Search-4 - Back Fow;ard Reload Slop Print B ,IH..cBookmarks eRed Hat Network dSupport EIShop GtProducts E jTraininq

The,uhtraction value of 134.57 - 12.0 =121.7

—:2 fDone

Figure 4.3 Displaying the Value of a Subtraction

A2 -Using the : : tocal , ."Va Var iables

A variable initialized and used inside a function is called a local variable. The declaration of localvariable and normal variable is similar. The l ifetime of a local variable begins when the function iscalled and ends when the function is executed. A local variable is declared inside a function and thevalue assigned is retained unt i l the funct ion executes.

Page 44 of 274 V 1.0 0 2004 Aptech Limited Web Scripting with PHP

Page 46: Web Scripting With PHP 1-12

APKC-CHSession 4 W - 0 R L W.W."310',E

Using Variables and Expressions in PHP

For example, to use local variables in the function that calculates sum of two variables:

In the above code, the variables, $intl and $int2 are declared inside the sum () function as thelocal variables of the function. They are initialized and used inside the function. The sum of twovariables, $inti and $int2 is calculated in the sum() function. This function executes when thePHP script calls the function using the function name.

Save the file as localvar.php under the.: directory.

Open the Mozilla Web browser.

Type http://localhost/localvar.php in` the address bar and press"the Enter key.

1. Open a new file in the text editor.

Enter the following code to create the sumo function:

<HTML> <HEAD> <TITLE>Local Variables</TITLE> </HEAD>

<BODY>

<?php

Web scripting with PHP V 1.0 © 2004 Aptech Limited Page 45 of 274

Page 47: Web Scripting With PHP 1-12

A P FEC117

Session 4 WORLDIWI-019

Using Variables and Express ions in PHP

-7—Local.varlables - Maz Ili -

File Edit View Go Bookmarks Tools Window Help

14 http:/Poca1host/localvar.lF,; Back Forward Reload Stop

1 -1 Home I *Bookmarks *#Red Hat Network (dSupport UAShop EtProducts ,C;ATrajnlnq

The sum of 43.4 + 13 = 56.4

Figure 4.4 : Using the Local Variables

4.3 Using the. Global Variables

When a variable retains its value throughout the lifetime of the Web page, it is called the globalvariable. The global variable is declared with the help of the keyword global within the function.As a result, it can be accessed from any part of the program.

For example, to use global variables in the function that calculates quotient of two integers:

Open a. new. file in the text editor.

Enter the following code to create the division() function:

<HTML> <HEAD> <TIITLE>Glbb al Variables</TITLE> </HEAD>

<BODY>

<?php

$intl = 68; $int2 = 50;

function division()

global $intl, $int2;

C-4Print

12— S ea rc h

Page 46 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP .

Page 48: Web Scripting With PHP 1-12

2PrintWpjAocalh.Wabt-j1-j &Sw=hj

Red liat`Ne -4 Home 1. Id Bookmarks APP 4 ! 19Prodixxts GATrjgg "..

V 1.0 C(;,, 2004 Aptech Limited I, Neb Scripting with PHP

Using Variables and Expressions in PHP

The quotient for 68/50 = 1.36

(D Done4 1 1 - - ' — — h

Figure 4.5 : Using Global Variables

4.4 Using the Static Variables

A static variable is similar to a local variable. The only difference is that the static variable retainsi ts value even af ter the funct ion terminates. When a function terminates, the values of the localvar iab les of that funct ion looses i t s values . To reta in the value of the var iable th roughout theexecution, use the STATIC keyword with the variable name.

Session 4

$int3 = $intl/$int2; echo "The quotient for $intl/$int2

4,14a,

I "' F1 y he. output fig""t

"Global Variables - M ill Elie Edit

(A—PT'ECH11woa LDWIDF

Page 49: Web Scripting With PHP 1-12

APF,'c_f'CN

W 0 A LD;WI:0,2

Session 4 Using Variables and Expressions in PHP

<HTML> < H E A D > <TITLE>Static </IIEAD>

1. Open a new file in the text editor.

2. Enter the following code to create the decrement() function:

In the above code, the static_intl variable is declared as the static variable. It is declared inside the decrement() function. The variable, stati-c—inti is local to the decrement() function but it retains its value throughout the program.

3. Save the file, as staticdec.php under the /var/www/htmi directory.

4. Open the Mozilla Web browser.

Type the http://localhost/staticdec.php key in the address bar and press

the Enter key. The output appears, as shown in Figure 4.6.

Page 48 of 274 V 1.0 @ 2004 Aptech Limited Web Scripting with PHP

Page 50: Web Scripting With PHP 1-12

Session 4 A P rECH

W-O•R'L 0 W I'D' •

Using Variables and Expressions in PHP

'S

File Edit View go Bookmarks Tools window Help -

h cvittp:

Ant — --------- ........ 1 - -- .............

: I } Home Nf Bookmarks JfRed Hat Network Support (IlShop dProducts dTridning The decrement value is 98

!'4. C , •-e, 04 G9 Done

F i g u r e 4 . 6 : D e c r e m e n t i n g a V a l u e

Web Scripting with PHP V 1.0 ng 2004 Aptech Limited Page 49 of 274

Page 51: Web Scripting With PHP 1-12

Using Variables and Expressions in PHP

ri

TRY: IT YOURSELF -- ____

Part II - For the next half an hour:

1. Store the string, I am learning PHP 4, in a variable and display it on the Web browser.

2. Create a form that accepts two numbers and displays its sum using the PHP script.

EalT7rEcmL D W I 0 , E

Page 50 of 274 V 1.0 ©2004 Aptech Limited Web Scripting

t~

Page 52: Web Scripting With PHP 1-12

Objectives

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

)> Use Arithmetic operators

Use Logical operators

Use Relational operators

,I> Use Bitwise operators

> Use Assignment operators

• Use String operators

Use Increment and Decrement operators

Introduction

All programming languages use operators. Operators are pre-defined symbols that allow performing specific actions. An expression contains operators and operands. The operators are assigned precedence values. This precedence value indicates the order in which the operators are evaluated in an expression.

In this session, we will learn about different types of operators such as arithmetic, logical, relational, bitwise, assignment, string, increment, and decrement- In addition, we will learn the operator precedence order.

5-16~rlttmiatio. Operators I ~E L

We use arithmetic operators to perform mathematical calculations. We follow certain rules while performing mathematical calculations. Similarly, PHP also follows certain rules. It is necessary to follow these rules so that different people get the same answer for an expression.

Consider the example below:

$Varl =21-4*4;

In the above expre-,sion, if we follow the order in which the operand appears, we get the answer as 68. Now if we follow the BODMAS rule of mathematics, the answer will be 5. PHP follows the similar BODMAS rules for calculation.

Web Scripting with PHP V 1.0 Oc 2004 Aptech Limited Page 51 of 274

Page 53: Web Scripting With PHP 1-12

AW01 p1t LYZEW

CAOME

Session 5 PHP Operators

PHP provides with the arithmetic operators, as shown in Table 5.1:

operator Name Description

+ Addition Adds the operands Subtraction Subtracts the second operand from the first operand Multiplication Multiplies operands with each other Division Divides the first operand by the second operand

Modulus Returns the remainder when the first operand is divided by

the second operand Table 5.1 : Arithmetic Operators

Some of the examples of the arithmetic operators are:

To display the sum of two variables, VAR1 and VAR2:

.<?php $VAR1=5; $VAR2=10; $SUM=$VAR1+$VAR2; echo "THE SUM OF 5 AND 10 IS: echo "$SUM";

Note the $Sum variable will store the sum of two variables, $VAR1 and $VAR2.

To display the product of three variables, $VAR1, $VAR2, and $VAR3-.

< ? -P h p $ V A R 1 = 2 ; $VZ%R2=1_0; $ V A R 3 = 1 0 ; $PROI)UC7'=$V"–'R1*$VAR2*$VAI'3; echo "THE PRODUCT OF 2, 10, AND 10 IS: echo "$PRODUCT";

Note the $PRODUCT variable will store the product of three variables, $VAR1, $VAR2, and $VAR3.

• To display the remainder:

<?php $VAR1-15; $VAR2=4;

Page 52 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Page 54: Web Scripting With PHP 1-12

141prAFCH

Session 5 WG*RIL D W I D

PHP Operators

$REMAINDER=$VAR1%$VAR2; echo "THE REMAINDER OF 15 DIVIEDED BY 4 IS:"; echo "$REMAINDER";

Note the $REMAINDER variable will store the remainder of two variables $VAR1 and $VAR2.

5.2 Relational Operators

A relational operator compares two operands. They determine the relationship between operands.Whenever we compare two values, it returns either true or false. PHP provides us with therelational operators, as shown in Table 5.2.

Operator Name Description Equal to Returns true if both the operands are equal 1= Not equal to Returns true if the first operand is not equal to

the second operand < Less than Returns true if the first operand is less than the

second operand <= Less than or equal to Returns true if the first operand is less than or

equal to the second operand > Greater than Returns true if the first operand is greater than

the second operand >= Greater than or equal to Returns true if the first operand is greater than

or equal to the second operand Table 5.2 : Relational Operators

For example, to compare two variables, enter the following code: < Php $A=74;

if ($A>$B)

echo "$A IS GREATER THAN $B";

else

echo "$A IS LESSER THI\d,4 $B";

The it statement executes a block of code only when the specified condition is true. Note the it keyword is followed by the condition. This condition compares two variables, A and B. If the variable A contains value greater than B, the code following the it statement will be executed.

Web Scripting with PHP V 1.0 nc 2004 Aptech Limited Page 53 of 27A

Page 55: Web Scripting With PHP 1-12

Session 5 :APFECM 0~WORLDWIDE

PHP Operators

Otherwise, the code following the else statement will be executed. The result of the above code will be A is greater then B.

5..3 'Logical Operators..

The Logical operators enable us to combine two or more test expression in a condition. Theyevaluate expressions and return a Boolean value. PHP provides us with the logical operators, asshown in Table 5.3.

Operator A N D

true O R

true X O R

Expression2 are true or if both Expressionl and Expression2 are false and true otherwise.

& & true

II E xp r e ss i o n l I I E xp r e ss io n2 R e t u r n s t r ue i f a ny on e o f t he e xp r e ss io n i s

I Table 5.3 : Logical Operators

Some of the examples of the logical operators are:

To check if the student has percentage greater than 60 and year of passing is 2003:

<?php $A=$–GET('PERCENTAGE'j; $B=$–GETl'PASSINGYEAR'1; if ($A>60 AND $B—"2003") echo "ELIGIBLE FOR ADMISSION";

Note the percentage and passing year inputs are accepted from the user. We want both the inputs to satisfy certain condition.

To use the OR operator:

<?php $A=$–GET['Valuc'1- if ($A=90 01t $A--95) echo "VALID INPUT";

Note the input value is accepted from the user. If the input satisfies the condition, the if body is executed.

Page 54 of 274 V 1.0 ©2004 Aptech Limited Web Scripting with PHP

Page 56: Web Scripting With PHP 1-12

Session 5

Et—SRI-ECM OR LDWIDE

PHP Operators

5.4 Bitwise Operators

The bitwise operators operate on the bits of an operand. They are similar to the logical operators.They work on small-scale binary representation of data. PHP provides us with the bitwise operators,as shown in Table 4.4.

Table 5.4 : Bitwise Operators

Some of the examples of the bitwise operators are:

To use the & operator on 15 and 5:

<?php echo 15&5;

Note the above code will return 5. To

use the A operator on 10 and 15:

<?php echo 101,15;

Note the above example will return 5.

Web Scripting with PHP V 1 . 0 O c 2 0 0 4 A p t e c h L i m i t e d Page 55 of 274 Operator Name General Form Description

Page 57: Web Scripting With PHP 1-12

APYLU'CH

Session 5 W,',0,1UL'0W1VD-Z

PHP Operators

-5.5 Assignment Operators',..

The assignment operator enables us to set the operand on the left side to the value of theexpression on the right side. The '=' sign is the assignment operator. It is different from the equal to'= 'sign used as the relational operator.

For example, to assign a value to a variable:

<?php $var1=52; $var2=10; $A =$var*$var2+8; echo "The value of A is:" echo "$A";

Note the above code will assign the value 528 to the variable $A.

5.6 Increment and Decrement Operators

The increment operators increase the value of the operand by one. The decrement operatorsdecrease the value of the operand by one. These operators function more effectively within loopssuch as for, do while, and while. PHP provides us with the increment and decrement operators, asshown in Table 5.5-

Operand Operator Name Description ++$a Pre-increment Increments the operand value by one and then

returns this new value to the variable $a++ Post-increment Returns the value to the variable and then

increments the operand by one —$a Pre- decrement Decrements the operand by one and then returns

this new value to the variable $a— Post decrement Returns the value to the variable and then

decrements the operand by one

Table 5.5 : Increment and Decrement Operators

Some of the examples of the increment and decrement operators are:

To use the post-increment operator on a variable $A: -1P . lip

$A=9;

echo "The value of A is: $A++ <BR>";

Page 56 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Page 58: Web Scripting With PHP 1-12

Session 5

AprEcAf

PHP Operators

e c h o " T h e v a l u e o f A i s : $ A " ;

Note the above code will return the value of $A as 9. It will then increment it to 10 and return this new value.

To use the pre-decrement operator on a variable $A:

<?php $A=1.0; e c h o ' T h e v a l u e o f A i s : $ A < B R > " ; –$A; e c h o " T h e v a l u e o f A i s : $ A " ;

Note the above code will return the value of $A as 10. It will then decrement it to 9 and return this new value_

5.7 String Op prators

The string operators operate on character data. PHP provide us with the string operators, as shown in Table 5.6.

Operator Name Description Concatenation Returns a concatenated string Concatenating assignment Appends the argument on the right side to the

variable Table 5.6 : String Operators

Some of the examples of the string operators are: To concatenate the strings WELCOME and FRIENDS using the Concatenation operator:

<?php

$A=WELCOME; $B= FRIENDS; $C="$A.$B" echo" CONCATENATED STRING IS $C-;

Note the above code will concatenate the strings and store it in a variable $C. The above code returns the string WELCOME FRIENDS.

Web Scripting with PHP V 1.0 @ 2004 Ar)tech Limited Page 57 of 274

Page 59: Web Scripting With PHP 1-12

'APFIEC

Session 5 WORLIDWIIIDIZ

PHP Operators

> To assign a value to a variable using the Concatenating assignment operator:

<?php $A=WELCOME; $A.= FRIENDS; echo" CONCATENATED STRING IS $A";

Note the above code will append the FRIENDS on the right side of $A containing the value WELCOME and return the string WELCOME FRIENDS.

5.8 :Precedence of Operators

We have seen the different operators in PHP. A complex expression may have several operators on it. In such cases, PHP will follow the order of precedence. Table 4.7 indicates the precedence of the operators.

Precedence Operators Highest Precedence % AND XOR

Lowest Precedence OR

Table 5.7 : Precedence of Operators

The operators listed on the same row have the same precedence.

For example, consider the expression below:

$A>60 OR $B==20

Now, in the expression above first the variables $A and $B are checked, whether they satisfy the required condition. Then the OR operator is used.

I

Page 58 of 274 V 1.0 9) 2004 Aptech Limited Web Scripting with PHP

Page 60: Web Scripting With PHP 1-12

Session 5

(A'P7-,FCHOR L D W I WE

PHP Operators

• Operator is any symbol that performs an operation on an operand.

An operator enables us to work on variables, strings, and numbers. >

Operators enable to control the program flow.

• In a complex expression, operator precedence indicates the order in which the operands must be evaluated. PHP evaluates operators with high precedence before operators with i low precedence.

The types of operators are:

• Arithmetic operators • Logical operators • Relational operators • Bitwise operators • Assignment operators • String operators • Incremental and Decremental operators

> The arithmetic operators work with numbers. They are used to perform mathematical operations. We follow the rule of BODMAS for operator precedence.

The relational operators compare two operands. They determine the relationship between operands. i

i

V 1.0 0( 2004 Aptech Limited > The logical operators handle multiple conditions. They combine two or more test expression in

a condition- They return a Boolean value. The Bitwise operators enable comparison and manipulation of operands. They operate on the bits of an operand. The assignment operator allows assigning a value to a variable. It enables us to set the operand on the letf side to the value on the right

side The increment and decrement operators. allows to increase or decrease value of an

I operand by one.

Web Scripting with PHP Page 59 of 274

Page 61: Web Scripting With PHP 1-12

APYIECH

Session 5 WORLDWJDE

PHP Operators

> The concatenation operator joins two or more strings into a single string. The string operators used in PHP are:

0 Concatenation operator ('.'): Returns the concatenation of its right and left arguments

Concatenating assignment operator Appends the argument on the right side to the argument on. the left side

Page 60 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

I

Page 62: Web Scripting With PHP 1-12

Session 5

(.-4Pr,FC,ffWORLDWIDE

PHP Operators

ruff YOUR R PROGRESS -U 1111 U 1% L M

1 is the symbol used to perform the operation on a value.

a. Operand

b. Variable

C. Operator

2. The ________ arithmetic operator returns the remainder of a division operation.

a. /

b.

C. $

d. None of the above

3. operators compare operands and determine relationship between operands.

a. Relational

b. Arithmetic

C. Assignment

d. Bitwise

5 operator is the concatenating assignment operator.

a.

b_

c.

e. = =

I Scripting with PHP

V 1.0 0c 2004 Aptech Limited 4

Page 63: Web Scripting With PHP 1-12

APFIECH

Session 5 WOR LVW I DE

PHP Operators

6. The operator returns true only if all the expressions are true.

a. AND

b. OR

C. XOR

7. The << operator ______________

a. Shifts the bits of Operand2, Operand-I times to the right

b. Shifts the bits of Operandl, Operand2 times to the left

C. Shifts the bits of Operandl, Operand2 times to the right.

d. Shifts the bits of Operand2, Operandl times to the left

Page 62 of 274 V 1.0 9 2004 Aptech Limited Web Scripting with PHP

Page 64: Web Scripting With PHP 1-12

Objectives

At the end of th is sess ion, you wi l l be able to :

• Use Arithmetic operators

Use Relational operators

Use Assignment operators

• Use Logical operators

Use Bitwise operators

Use String operators

Use Increment and Decrement operator

The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives, are met and the understanding of the tool is complete: Please follow the steps carefully.

Part I - For the first 1.5 Hours:

Using the .Arithmetic Operators

We use arithmetic operators to perform mathematical calculations. The arithmetic operators include operators such as addition, subtraction, multiplication, division, and modulus_

Forexample, to create a form that accepts two numbers and displays their product using the PHP script-.

1. Open the gedit text editor.

2. Enter the following code to create a form that accepts two numbers:

<HTML> <BODY> <B>Multiplication of Two Numbers</B> <FORY1 METHOD=GET ACTION "Multiplication.php"> Enter the First Number: <INPUT TYPE="TEX'1'*" NAME="n1text"> <RR> Enter the Second Number: <INPUT TYPE="TEXT" NAME="r12text">

Web Scripting with PHP V 1 . 0 • 2 0 0 4 A p t e c h L i m i t e d Page 63 of 274

Page 65: Web Scripting With PHP 1-12

Session6

CAP"0 R L D FW CI O N-F

PHP Operators

<INPUT TYPE="SUBMIT" VALUE="MULTIPLY" <BR> </BODY> </HTML>

Save the file as multiply.htmi under the /var www/html 'directory. Open a new file in the text editor.

Enter the following code to multiply the numbers:.

<?php $A=$_GET['.n1text'j; $B=$__QET['n2text'l; $C=$A*$B; echo "The multiplication-of- two.- numbers is $C";

t ,1bd--tft"Wnd th ht41-:-, direct()a d" e 0111-

V,, : W'D

rowt er •

zi

File Edit View Go Bookmarks Tools window Help

AN S-i I t (1) p1 , 4 httl:i:/AocaIhostjMuItip !.,--Search 4 - - - _ - P r i n t Back Forward Reload

!tj Home Bookmarks - R e d Hat Network (,]ftsupport ( : I S h o p (j_IProducts jElTraining

IN I till iplicatio 11 of "Fwo Numbers tillibel-S Fnwi the First Number: Enter the Second Number: I

MULTIPLY (92i Done

Figure 6.1 : Multiplication Form

9. Enter the first number as A. 10. Enter the second number as 59.

11. Click the MULTIPLY button. The output appears, as shown in Figure 6.2.

Page 64 of 274 V 1.0 * 2004 Aptech Limited Web Scripting with PHP

Page 66: Web Scripting With PHP 1-12

Session 6APKECRI, WORLD 102

PHP Operators

Figure 6.2 : Viewing the Product

6.2 Using to Relational Operators Using Operator

relational operator compares two operands. They determine the relationship between operands. Whenever we compare two values, it returns either true or false.

For example, to create a login form that accepts the username and password and authenticates the user using the PHP script:

1. Open a new file in the text editor.

2. Enter the following code to create the authentication form:

< H T M L > < B O D Y > <B>Authentication</B> <FORM METHOD=GET ACTION "Authentication.php"> ENTER USER NAME: <INPUT TYPE="TEXT" VALUE="NAME"> ENTER YOUR PASSWORD: <INPUT TYPE="TEXT" VALUE="Passtext"> <BR> <INPUT TYPE="SUBMIT" NAME "CONFIRM" VALUE="CONFIRM'> <BR> </BODY> </HTML>

3. Save the file as AUthentication.html under the /var/www/htmi directory.

4. Open a new file in the text editor.

Web Scripting with PHP

V 1.0 (c) 2004 Aptech Limited Page 65 of 274

V,Mozilla,

Edit View Go Bookmarks Tools Window Help 4 3 '11 f,&, http:/Aocalhost/Multip ;A_Search

Page 67: Web Scripting With PHP 1-12

Air Eck

Session 6 w 0 ft:L 0 W 10.2

PHP Operators

5. Enter the following code to confirm the password,:

<HTML> <BODY> <?php $A=$--GET.['lDasstext'1

i f ($A--"pass" )

e c h o " V a l i d U s e r " ;

4 N I 1K on'*'- P]

6 ~ . b r o e r v

~-tn jrx

http:/Aocalhost/ Search Back Forward Reload S t o p Print

I fa Home I Xf Bookmarks e Red Hat Network (El supportShop (El Products (SITrajninq

Authentication

• E N T E R U S E R N A M E

E N T E R Y O U R P A S S W O R D :

C O N F I R M I

-F--

X ~ Z1 C = Z 3 ( F 9 1 1

Figure 6.3 : Authentication Form

9. Enter John as the user name.

10. Enter pass as the password.

11. Click the CONFIRM button. A page appears, as shown in Figure 6.4.

I %#

I

: File Edit View Go Bookmarks Tools Window Help

Page 66 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Page 68: Web Scripting With PHP 1-12

S e s s i o n 6W - Q , R - L ~ , D . W 1 1 D E

PHP Operators

File Edit View Go Bookmarks Tools

Window Help

http:/Aocalhost/Authelv Search w Back Forward Reload Stop Print

!ill Home I V4Bookmarks .t Red 'Hat Network Support ( AS h o p O' Products CjTraining Valid User

LZ -,?, -04 (2~2 Done F

Figure 6.4 : Viewing the Confirmation

6 .3 Us ing the . a l Opera tors L2 W-C Operators

The Logical operators enable us to combine two or more test expression in a condition. They evaluate expressions and return a Boolean value.

For example, to create a form that accepts the percentage scored by the student and displays the grade depending upon it using the PHP script:

1. Open a new file in the text editor.

2. Enter the following code to create the form:

< H T M L > < B O D Y > <B>Grades</B> <FORM METHOD=GET ACTION "Grade.php"> ENTER YOUR PERCENTAGE: <INPUT TYPE="TEXT" VALUE="n1text"> <BR> <INPUT TYPE="SUBMIT" NAME=;"GRADE" VALUE="GRADE"> <BR> </BODY> </HTML>

3. Save the file as Grade .html under the /var/www/htmi directory.

*JVeb Scripting with PHP V 1 . 0 C c ) 2 0 0 4 Aptech Limited P a g e 6 7 o f 2 7 4

Page 69: Web Scripting With PHP 1-12

Session 6 (A_____ PrEcirf0 WORLDWIDE

PHP Operators

Enter the following code to assign grades:

h, $A,$_BT['nitext'];

i f 6 0

........

-,v

Save the file as Grade. php','. under-, the tvar/mm/html directory.,,,,.

Open the Mozilla Web browser.

Type http://loc.alhost/Grade..html in the address bar and press the Enter key. A page appears 'prompting to enter the percentage, as shown in Figure 6.5.

Figure 6.5 : Grade Form

ozilla 'XFile Edit View Go Bookmarks Tools Window Help i

___ IBack Forwar 5 httnAocalhost/Grade h fv]Reload Stop -a Search

Pant U —

UU.'.Home VI Bookmarks t R e d Hat Network (2ftSupport Shop (ItProducts LljTralning

Grades ENTER YOUR PERCENTAGE GRADE

- - - ------- --------- -- . ........ .-04 eg 1' Done L

Page 68 o f 274

Page 70: Web Scripting With PHP 1-12

Session 6 A p r E c m

WORLDWIDE

PHP Operators

8. Enter 70 I ' ENTEWiYOUR PERCENTAGE text box.

9. Click GRADE A shown GRA E. button. p~ge, appears, as sh n in Figure 6.6.

IFn Irk f1v

Filedif View Go Bookmarks Tools Window Help

.4i htt Itlocalhost/ ' Back Forward Reload Stop _____ V V ,;.*,Search Print

!*Rome 1 IdBookmarks -AtRed Hat Network (;'Support dShop EftProducts (RTralnlng

Congrats'!! Grade I

K*V , 1-1 1 1 - ; -1 1lf@. G9. Done

Figure 6.6 : Viewing the Grade

6.4 Using the Assignment Operator,

The assignment operator enables us to set the operand on the left side to the value of theexpression on the right side. The '=' sign is the assignment operator. It is different from the equalto '= 'sign used as the relational operator.

For example, to create a form that accepts the principal amount, interest rate, and no. of years and calculates the simple interest using the PHP script:

1. Open a new file in the-text editor.

2. Enter the following code to create a form:

<HTML> <BODY> <B>Simple Interest</B> <FORM METHOD=GET ACTION "Simpleinterest.php"> ENTER THE PRINCIPLE AMOUNT: <INPUT TYPE="TEXT" NAME=" n1text" > <BR> ENTER THE RATE OF INTEREST: <INPUT TYPE="TEXT" NAME="n2text"> <BR>

Web Scripting with PHP V 1.0 (D 2004 Aptech Limited Page 69 of 274

Page 71: Web Scripting With PHP 1-12

S e s s i o n 6 Eaii:FECHL,0W1,0-E

PHP Operators

ENTER THE NUMBER OF YEARS: <INPUT TYPE="TEXT" NAME="n3text"> <BR>

<1 NPUT <BR> </BODY> </HTML>

di Save the file as situp14inter'68t html,'.. under the /var/ rector Enter the following code to calculate the.. simple interest:,,

< ?php $ P = $ — G E T [ ' n i t e x t ' j ; •

$R=$-" GET ['n2 text ']--

$N,:7,$_QET['n3 text '1; ci l r~L ' y V ($ P $ R-' 0

"CALCULATE" VALUE="CALCULATE">

7. Type http://localhost/Simpleillterest.htmi in the address bar 'and press the Enter key. The form appears, as shown in Figure 6.7.

Figure 0.7 : Simple Interest Form

8. Enter 30000 in the Principal Amount text box.

9. Enter 3.5 in the Rate of Interest text box.

Page 70 of 274 V 1.0 @, 2004 Aptech Limited Web Scripting with PHP

Page 72: Web Scripting With PHP 1-12

Session 6

CA—PTECK R O'LDWI-DE

PHP Operators

10. Enter 5' in the Rfirnber of Years text box.

11. Click LATE button. A page appears, as shown in Figure 6.8. U.

Figure 6.8 : Viewing the Calculated Simple Interest

6.5 Using tie B&IM" e OMgWrs

The bitwise operators operate on the bits of an operand. They are similar to the logical operators_ Theywork on small-scale binary representation of data.

For example, to use the OR operator on 32 and 5 using the PHP script:

1. Open a new file in the text editor.

2. Enter the following code:

<?php echo "THE ANSWER OF 3215 IS : echo 3215;

3. Save the file as bitwise.php under the /var/www/ht-ml directory.

4. Open the Mozilla Web browser.

5. Type http://localhost/bitwise.php in the address bar and press the Enter key. A output appears, as shown in Figure 6.9.

V 1 . 0 6, c ) 2004 Aptech Limited P a g e 7 1 o f 2 7 4

Mozillia

File Edit View Go Bookmarks Tools Window Help . ................. ... . .....

L4 http:/Aocalhost/Si.phllvl ______ ( 4 Back Forward Reload --Search Print ....... .......... . f o l Home I Vj Bookmarks je Red Hat Network (:rjsupport Shop Products 6jTralnlng

T14E CALCULATED SIMPLE INTEREST IS 5250

LZ 't~ Q 09 1 Dom

W e b S c r i p t i n g w i t h P H P

Page 73: Web Scripting With PHP 1-12

Sessocn 6

PHP Operators

Sv 44o Ila File Edit View Go Bookmarks Tools LMndow Help .. . .. ........ ttp:/flocallio -h

Back Fonvard Reload Stop I--

_____________________________________________________________________________________________________________________________________________________ Print B 011 ijj Home i Xf Bookmarks #*Red Hat Network EtSupport C,-~,Shop C jProduus EIT wining

THE ANSWER OF 3215 IS: 37

U~ . ..... . .... Figure 6.9 : Viewing the Result of using Bitwise Operator

"6.6 Using' ..the .String Operators-

The string operators operate on character data. PHP provides two string operators to concatenate two or more strings.

For example, to append text to the existing string: , W,

IneW 11

2. El-60"rIfiii: following code: <?php $ S t r i n g = " H E L L O " ; $String.= " FRIENDS";echo "$String .........

ext"'.1

3. Save the file as string.php under the /var/www/htm1/ directory.

4. Open the Mozilla Web browser.

5. Type http.- / / localhost /String. php in the address bar and press the Enter key. A page appears, as shown in Figure 6.10.

Figure 6.10 : Appending Text to a String

File Fdit View Go Bookmarks Tools Window Help 7 3- hap:1pocalhost/Strin Search C4

Back Forward Reload S t o p Po— Print /,JHonie )dBookmarks *Red Hat Network 6Support [ j Shop L-'Products 'Training I I I'LL0 FRIENDS ... ""'

C.-D t:42

Page 72 of 274 V 1.0 `Q 2004 Aptech Limited

Page 74: Web Scripting With PHP 1-12

Session 6

ePYWCH R L,11) W 1 0 E

PHP Operators

6.7 Using the Increment and Decrement Operators

The increment operators increase the value of the operand by one. The decrement operators decrease the value of the operand by one.

For example, to display the value of the variable before and after using the pre decrement operator:

1. Open a new file in the text editor.

2. Enter the following code:'

5. Type http://localliost/I)ecr*ement.pbp in the. address 'bar and press -the-Enter key. A page appears, as shown in Figure 6.11.

V 1 F i l e E d i t V i e w G o B o o k m a r k s T o o l s W i n d o w H e l p

3 411tip:I/localhost/ crenjR wt., search Back F :.,- ; J Reload S T L - i ______________________________ Print

fl Home j Bookmarks#*-*Red Hat Network ;~f Support -'Shop ' d 2 i i jI hc vain,: of A is 1 (10 'I I

ic x aluc ol'A is 99

M c--2 i Done t

Figure 6.11 : Viewing the Result of Decrement

i

.'.eb Scripting with PHP

Page 75: Web Scripting With PHP 1-12

Session 6(1AJi7T'ECM

WORLD WIDE

PHP Operators

Part II - For the next half an hour:

1. Create a form that accepts the first name, last name, and the basic salary of the employee.

2- Write a PHP script to display the full name and basic salary of the employee.

3. Also, calculate and display Dearness Allowance (DA), HRA, and TAX. The DearnessAllowance is calculated at 2% of the basic salary, while HRA is calculated at 5% of thebasic salary. The tax is deducted from the salary based on the range of the basic salary.

4. In addition, calculate the net salary of.the employee using the following formula.

Net Salary = Basic Salary + DA+ HRA - TAX

V 1.0

C~,'

2004

Aptech

Limited

Range Page 74 of 274

Page 76: Web Scripting With PHP 1-12

nditional StOleaments

J in P Hip Obi ectives

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

Use the If statement

• Use the Switch statement

Use the Ternary (?) operator

rdd;"

In a programming language, flow refers to the order in which the statements in a program execute. In a program, the statements execute in a sequence, from the first to the last statement. We can use conditional statements to change the order of flow in a program. The conditional statements execute a set of statements only when a specified condition is satisfied. Conditional statements are also known as control statements as they control the flow of the program.

In this session, we will learn how to use the different types of conditional statements, such as if and switch statement. In addition, we will also learn to use ternary operator in PHP.

7.1 i f St l t The if statement executes a block of code only when the specified condition is true. If the condition is false, the block of code is ignored. For example, a registration form gets accepted only if a user specifies the full name and email address_

Thesyntax for if statement is:

i f ( cond i t i on ) C o d e e x e c u L e s i f t h e c o n d i t i o n i s t r u e ;

The if keyword is followed by the condition in parentheses. The condition is the test expression consisting of variables and operators- If the condition is satisfied, the code in the if body i8 executed.

For example, to compare two variables and display a message:

o dy >

< ? P P $a=10;

Web Scripting with PHP V 1.0 (q) 2004 Aptech Limited Page 75 of 27,11,

Page 77: Web Scripting With PHP 1-12

SessiAPTIECHWO R L D.W 1 0 n

Conditional Statements in PHP

$b=12;

if ($a < $b) echo "a is less than b";

</body> </html>

If more than one statement is to be executed when the condition is true, we must enclose the statements within the curly brackets.

For example, to find and display the bonus at the rate of 10% and total salary when the salary of the employee is greater than 8500:

<html> <body> <form action="salBonus.php" method="GET"> <table) <tr> <td>Salary </td> <td><input type="text" name="sal"></td> </tr> </table> <br>

<input type="submit" value="Submdt">

< / f orrrL> </bodv> </html>

Save the above code as SalBonus.html. To process the salary, use the following PHP code:

<?php

$sal=$_GET['sa].'];

echo "Salary before bonus $"; echo ssal; echo "<br>";

10

it ($sal > 8500) f

$bonus = Ssal * .1; echo "Bonus : 1"'

Page 76 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Page 78: Web Scripting With PHP 1-12

Session 7 (A—PFECH

WORLDWIDE

Conditional Statements in PHP

echo "<br>"; $sal = $sal + $bonus; echo "Total Salary : $$sal";

Note if the salary of the employee is less than 8500, the statements within the curly brackets are not executed. The statement that follows the closing curly bracket (1) will be executed.

We can execute a block of code when the specified condition is false. This can be done using the else statement. The else statement is used along with the if statement.

The syntax for if...else statement is:

-if (condition),,

Code executes if the condition is true

else

Code executes if the condition is false

For example, to calculate the commission at the rate of 10% when the sale is greater than 20000 and at the rate of 5% when the sale is lesser than 20000.

The following code calculates the commission:

if'($sales > 20000)

$comni = $sales * .1; echo "Cormision $$coaun"

else($sales < 20000)

$comm = $sales .05; echo "Cormision $$conun";

In the above code snippet, the $sales variable stores the sales amount and the $comm stores the amount of commission. When the sales amount exceeds 20000, the program executes the -- f statement and calculates commission at the rate of 10%. When the sales amount is less than 20000, the program executes the else statement.

V 1 .0 © 2 0 0 4 Ap tech L im i t ed Page 77 of 274

c -:'---ipting with PHP

Page 79: Web Scripting With PHP 1-12

Session 7 (A-JMFECAr 1-!~~ LOW71,0E

Conditional Statements in PHP

We can also use elseif clause along with if statement. The elseif clause is an optional clause that allows testing alternative conditions- It is executed before the else statement.

For example, to calculate the commission based on the rates specified in Table 7.1-.

Table 7.1 : Commission Rate based on Sales

The following code accepts the sales amount from the user:

<html> <body> <form action="SaleComm.php" method="GET">

<table> <tr> <td>Total Sales </td> <td><input type="text" name="sal"></td> </tr> </table>

<br> <input </forni> </body> < / h L

="submit" value="Submit'>

Save the above code as SaleComm-htm]. To process the sales amount and calculate the commission, use the following PHP code:

<?php

$sal=$–GET['sa1.'];

echo "Total Sales echo $sal; echo "<br>";

if ( $ S a l > 50000)

Sales Commission Rate

Page 80: Web Scripting With PHP 1-12

Session 7 APTIECIf

WORLDWIDE

Condit ional Statements in PHP

$comm = $sal echo $$comm"; cno "Commission echo "<br>";

I

elseif ($sal > 20000 and $sal <= 50000)

$comm = $sal * .07; echo "Commission $$comm"; echo "<br>";

else ($sal < 20000)

$comm = $sal * .05; echo "Commission $$comm"; echo -<br>";

I

In the above code, commission is calculated according to the sales amount that the user enters. For example, if the user enters 55000, PHP displays the following message:

Total Sales $55000 Commission $5500

We can also specify if statement within if statement or else statement. These are known as nested it statements.

For example, to calculate the electricity charges based on the units specified in Table 7.2:

Units Rate($) Above 1000 3 Greater than 500 but less than equal to 1000 2

Lesser than 500 1.5 Table 7.2 : Electricity Charges based on Units

Also, add service charges at the rate of 10% on the electricity charges paid when the amount exceeds 2000.

,'.Ieb Scripting with PHP V 1.0 C0 2004 Aptech Limited Page 79 of 274

Page 81: Web Scripting With PHP 1-12

W O R L D W I D E

14PTECH Sessuon 7

Conditional Statements in PHP I I I I I I I I I I I I I IN W , ___________________________________________________________________________________________________________________________________________

Following code accepts the number of units consumed by the user:

<html> <body> <form action="elecBill.php" method="GET">

<table> <tr>

<td>Number of Electricity units consumed </td> <td><input type="text" name="units"></td>

</tr> </table>

<br> <input type="submit" value=-Submit">

</form> </body> </html>

Save the file as elecBill.html. To find the total electricity bill, use the following code:

<?php

$units=$_GET['units'1; echo "Number of Units consumed echo $units; echo "<br>";

if ($units > 1000)

$rate = $units * 3; $service = $rate

echo "Service Charge added for units above 1000 $$service"; echo "<br>"; $totalbill = $rate A - $service; echo "Total Electricity Bill : $$totalbill";

} else

if ($units > 500 and $units <= 1000)

$rate = $units * 2; echo "Total. Electricity Bill $$rate";

else

I ;

Page 80 of 274 V 1.0 Q 2004 Aptech Limited Web Scripting with PHP

Page 82: Web Scripting With PHP 1-12

Session 7CConditional Statements in PHP

$rate = $units * 1.5; echo "Total Electricity Bill $$rate";

Save the above code as elecBill.php. In the above code, if the user enters 1500, PHP first calculates the rate and stores the value in $rate variable. To calculate the service charge charged on the electricity bill, PHP calculates the service charge at the rate of 10% and store the value in $service. It then stores the total amount in the $totalbill variable.

If the user enters number of units as 400, the total electricity bill would be calculated at the rate of 1.5. The output would be, Total Electricity Bill $600-

7.2 Switch Statement

A switch statement checks single variable against multiple values and executes a block of codebased on the value it matches. The value can be any integer or string constant. The switchstatement is easier to read than multiple if statements.

The syntax for the switch statement is:

switch(variable)

case valuel: Code executes if condition equals valuel break;

case value2: Code executes if condition equals value2 break;

default: Code executes the variable does not matches any specified value

The switch statement is followed by the variable in parenthesis. The case keyword is followed by a case constant. The case constant can be an integer or string constant. The data type of the case constant must match the data type of the switch variable.

Before entering the switch statement, program must assign value to the switch variable. The switch statement implements the code statement by statement. The switch statement executes the code only when the value of the case statement matches the value of the switch variable. PHP continues to execute the statements until the end of the switch statement or until a break statement.

Page 81 of 27,1

Neb Scripting with PHP V 1 . 0 O c 2 0 0 4 A p t e c h L i m i t e d

Page 83: Web Scripting With PHP 1-12

APT,ECH

WORLOWIVE

C on d i t io n a l S t a t e m e n t s i n P H P

The break statement is used to move the control to the statements following the switch statement. If the break statement is not used, PHP executes all the statements including the statements of the following cases in the switch statement.

The default is the special case. It is used when none of the case statements matches the value of the switch variable. We must place the default case after all the case statements in the switch statement.

For example, in the following code there are no break statements:

<?php $day = $–GET['day'l;

switch ($day)

case 1: echo "It's Sunday";

case 2: echo "It's Monday";

case 3: echo "It's Tuesday";

case 4: echo "It's Wednesday";

case 5: echo "It's Thursday";

case 6: echo "It's Friday";

case 7: echo "It's Saturday";

default: echo "There are Seven Days in a Week";

In the above code, if the user enters 4 as the week day, PHP first matches the case value that the user enters. If the user enters 4 as the week day, PHP displays the message related to case 4. It also displays all the messages related to the subsequent cases till it reaches the end of the switch statement.

The break statement instructs PHP to stop its action and come out of the switch statement. The statements following the switch statements will be executed.

The above code with a break statement:

<?php $day $-GET[ 'day'] ;

Page 82 of 274 V 1.0 Cc., 2004 Aptech Limited Web Scripting with PHP

Page 84: Web Scripting With PHP 1-12

Session 7 ARY'ECH

WO R-L DWI D E

Conditional Statements in PHP

switch ($day) { case 1:

echo "It's Sunday"; break;

case 2: echo "It's Monday"; break;

case 3: echo "It's Tuesday"; break;

case 4: echo "It's Wednesday"; break;

case 5: echo "It's Thursday"; break;

case 6: echo "It's Friday"; break;

case 7: echo "It's Saturday"; break;

default: echo "There are Seven Days in a Week";

break;

In the above code, if the user enters 4 as the week day, PHP displays only the message related to case 4- If the user enters any other value apart from numbers between 1 to 7, PHP displays There are Seven Days in a Week.

7 .3 Ternary (?) Opera lhbr - ' : '

Ternary operator is also known as conditional operator. It simplifies complex conditions into one line statements.

The syntax for the ternary operator is:

Terml ? Term2 : Term-3; .

Ternary operator requires three operands. It evaluates the condition specified in -Ter.mi and returns '1,erm2 if the condition is true and Term3 if the condition is false.

V 1.0 .7 2004 Aptech Limited Page 83 of 274 Scripting with PHP

Page 85: Web Scripting With PHP 1-12

Session 7 I WORLD PRLrD1 EW CID MAE( *

Conditional Statements in PHP

For example, consider the following code snippet with the ternary operator:

(7 == 7) ? "Yes" "No"_

In the above code snippet, Term1 includes an expression where number 7 is compared to 7. The value of Term2 and Term3 is, Yes and No.

Ternary operator is considered as a shortcut for if. ... else statement. Note the following code where the two variables are compared and the greater number is displayed using if ... else statement:

<?php $x = 100; $y = 50;

if ( $ X > $Y)

echo "X is greater than Y";

else

echo I is greater than X";

When the above code is executed, x is greater than Y is displayed. We can display the same output using the ternary operator. To use ternary operator instead of using if ... else statement:

<?php

$x = 100; $y = 50;

$disp = ($x > $y) ? "X is greater than Y" "Y is greater than X";

echo $diso;

Web Scripting with PHP

The above code also displays, x is greater Lhan Y.

Page 84 of 274 V 1.0 © 2004 Aptech Limited

Page 86: Web Scripting With PHP 1-12

Session 7

(A—PrECHD W 1 0 a

Conditional Statements in PHP

Web Scripting with PHP V 1,0 @ 2004 Aptech Limited T e r n a r y

Conditional statements change the order of flow in a program.

Conditional statements. execute a set of statements only when a specified condition is satisfied.

The i f statement executes a block of code only when the specified condition is true.

),- In a Nested if statement, we specify,if statement within if statement or else statement.

A switch statement checks single variable against multiple values and executes a block of code based on the value it matches.

The break statement is used to move the control to the statements following the switch statement.

The default statement is used when none of the case statements matches the value of the switch variable.

I

Page 87: Web Scripting With PHP 1-12

Session 7 CA - p r , E r i v - D E 1 0 M .

Conditional Statements in PHP

CHECK YOUR PROGRESS

a. condition

b. operator

C. variable - 1 declaration U.

1. The if keyword is followed by the _____________________ in parentheses.

2. executes a set of code only when a condition is true.

a. If statement

b. Switch statement

C. Conditional statement

d. Ternary operator

3. are used when there are many conditions with discrete values.

a. If statements

b. Switch statements

C. Conditional statements

d. Ternary operators

4. is used when none of the case statements matches the value of the switch variable.

a. Ternary operator

b. Switch statement C. Break statement

I d. Default statement

5. PHP continues to execute the statements in a switch statement until the end of the switch block or until it encounters the ____________ statement.

a. If

b. Default

C. Continue

! d. Break

Page 86 of 274 V 1.0 1 2004 Aptech Limited Web Scripting with PHP

Page 88: Web Scripting With PHP 1-12

Session 7

WORLDWIDE

APFECHConditional Statements in PHP

V 1.0 @ 2004 Aptech Limited Page 87 of 274

6. simplifies complex conditionals into one line statements.

a. If statement

b. Switch statement

C. Conditional statement

d. Ternary operator

'Aleb Scripting with PHP

Page 89: Web Scripting With PHP 1-12

Objectives

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

Use the -if statement

Use the switch statement Use

the Ternary (?) operator

The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully.

Part I - For the first 1.5 Hours:

8.1 Using the if

The if statement executes a block of code only when the specified condition is true. If the condition is false, the program ignores the block of code in the if body and executes the statements following the if body.

We will create a form that accepts name and phone number from the user. We will also add validation to the form to check if the fields in the form are left blank using if ... else statement.

To create the form:

1. Open the gedit text editor.

2. Enter the following code to create a form consisting of two fields, Name and Age:

<HTML> <HEAD> <TITLE>Personal Details</TITLE> </HEAD>

<BODY> <1-14>Please enter the information</H4>

<FORM> <table>

<tr> <td>N,aaie: </td> <td><input type="texL" name="myname"> </td>

Web Scripting with PHP V 1.0 (0, 2004 Aptech Limited Page 89 of 274

Page 90: Web Scripting With PHP 1-12

S e s s i o n 8 W 0 R L:D'W. UWE

Conditional Statements in PHP

Ln 8, Col. 41 INS

Figure 8.1 : Attributes of Form Element

4. Save the file as info.html tinder the /var/www/html directory.

5. Open a new file in the4ext editor.

</tr>

<tr> <td>Age: </td> <td><input type="text" name= "myage"></td> </tr>

</table>

="submit" va;~e='~,.Submit"><br> <iput

</FORM>

e a c u t e A h A ' I D t %is ie aclfior

9! .7,T -at M 0511

019 MIRI nse le

-Untitledl(-M odifie'd) - gedit

New Open - Save ' Print ' Undo Redo ' Cut Copy Paste ' Find Replace

Untitled 1, x <HTML> <HEAD>

<TITLE>Personal Details</TITLE> </HEAD> <BODY> <H4> Please enter the information </H4>

<FORM ACTION="dispDet.php" METHOD="POST$

<TABLE> - - <TR>

<TD>Name:</TD> <TD><INPUT TYPE="text" NAME="myname"</TD>

</TR>

P a g e 9 0 o f 2 7 4 V 1.0 @ 2004 Aptech Limited Web Scripting with PHP

Page 91: Web Scripting With PHP 1-12

A R rA Ec I f Session 8

Conditional Statements in PHP

6. Enter the following code to retrieve the information from the form and store them in variables:

ec ether, thdfflatni-q~41

z. . 11 .

After adding the code, the file appears as shown in Figure 8.2.

Figure 8.2 : Validating the Name

V _Unf id 'd. I f t o A l f i a Z- j edit, Nn . XFile Edit View Search Tools Documents Help

New Open Save Print Undo Redo Cut Copy Paste Find Replace

J, info.html x Untitled 11 x

<HTML> <HEAD>

<TIT LE> User In format ion , < /TITL E> </HEAD>

<BODY> <?php

$nivnarne =$—POST[ 'Mynarne'] S1r1yage=$_POST['rnyage'1;

e c h o " P l e a s e e n t e r y o u r n a m e " ;

L11 18. Col. I !NS

lejeb Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 91 of 274

Page 92: Web Scripting With PHP 1-12

AkEPYHCH

W-Oft L:D WTV4E

S e s s i o n 8 _________________ Conditional Statements in PHP 41

8.E ntWihe following code immediately after the if body to check whether the Age field is not left blank:

10.'. Save the file a.,4: dispDet.php under the /var/www/htmI--': directory.

11. Open the Mozilla Web browser.

1.12. Type hittp://localhost/info.html in the address bar and press the Enter The Personal. Details form appears, as shown in Figure 8.3.

Figure 8.3 : Personal Details Form

Submit I

IG2 T Done

V F i l e E d i t V i e w G o B o o k m a r k s T o o l s W i n d o w H e l p

4 - - 3 - 3 .1 4' h ttp:jjocalho51Anfo.J` _ I ;.—*Search

C-413 Home Y4 Bookmarks **-Red Hat Network C,ft. Support (AShop C~~jtProclucts Training

Please enter the information

Name: Ale:

P a g e 9 2 Of 274 V 1.0 © 2004 Aptech Limited

Page 93: Web Scripting With PHP 1-12

Session 8 APr,ECM

WOMILDWIDE

Conditional Statements in PHP

13. Click the Submit button. A page appears prompting to enter the name, as shown in Figure 8.4.

atio .),;. oz a,-,, 'Se ..Useffinf6im - 6 "A File Edit .,36ew Go Bookmarks Tools Window Help

3 h"p://localhost/dispElBack Forward Reload Stop _,& C-4 Print

- 1 Home i *4Bookmarks " R e d Hat Network -CTjSupport(!-~,Shop d'Products (:ITraining

Please enter your name

Back

L L •.,e- 0 (S9 [ Done

Figur Figure 8.4 : Message Displayed

It

--'sOi

File Edit View Go Bookmarks Tools Window Help http:ffiocalhostidisr[-j exSearchi

I Back Forward Reload Stop Print ~.)Home 4Bookmarks g*-Red Hat Network riSupport f-.jShop "Products t:jTraining

John, you did not enter your af!c

Rack aCk-

[)one

Figure 8.5 : Message to Enter Age Details

User Information - M ill

16. Click the Back hyperlink to return to the form.

17. Enter John in the Name text box and 44 in the Age text box.

18. Click the Submit button. A page appears, as shown in Figure 8.6.

Scripting with PHP V 1.0 10c 2004 Aptech Limited Pa ge 9 3 o f 2 7 4

Page 94: Web Scripting With PHP 1-12

APIFIECH

Session 8 W10MV-91WIV-1a

Conditional Statements in PHP

V . - -... ~ f'. fl. - I-., —1-v-11-~" -- 1 ' r n f X , V * Ij -rma onz girl

File Edit View Go Bookmarks Tools Window Help

,_,* Search C-:1

! H o m e I VjBookmarks e R e d Hat Network Support EJShop ( y Products ejTralning

Hi John. Your aye is 44

Back

L

Figure 8.6 : Personal Details Displayed

W -- --W - 8.2 Using the switch Statement.

A switch statement checks single variable against multiple values and executes a block of code based on the value it matches. The value can be any integer or string constant. The switch statement is easier to read than multiple if statements.

For example; an organization provides various facilities and perks to their employees depending on the grade assigned to them. Table 8.1 lists all the facilities available for the respective grades.

Grade Facilities A 1. Increments are based on 30% of their basic salary 2. Bonus at the rate of 20% of their basic salary 3. Traveling allowance worth $500 4. Medical allowance worth $500 B 1. Increments are based on 20% of their basic salary 2. Bonus at the rate of 10% of their basic salary 3. Traveling allowance worth $300 4. Medical allowance worth $300 C 1. Increments are based on 10% of their basic salary

2. Bonus at the rate of 5% of their basic salary 3. Traveling allowance worth $100

4. Medical allowance worth $100

Table 8.1 : Facilities Based on Grades

Page 94 of 274 V 1.0 (D 2004 Aptech Limited Web Scripting with PHP

Page 95: Web Scripting With PHP 1-12

S e s s i o n 8

APMr,MW 10 it L 0 WIM S

To display facilities according to the grades using the switch statement:

Open the gedit text editor.

Enter the, following HTML* code to create a form that accepts the name and grade Of an employee:

<HEAD> <TITLE> Grade Details <iTITLE>.

</HEAD> <BODY>

<H4>. Please enter the information </H4> <FORM>

<TABLE> TR k xg W Y34aMe p W. *A

V V , 4; ogt~ S.

0

(1010 ra e, A

TD>-;~'INPUT 'TYPE= "text" ~N' ;:~ gradEi"></TD>

.Veb Scripting with PHP V 1.0 ©2004 Aptech Limited

Page 96: Web Scripting With PHP 1-12

Session 8 6-4-~:ry-,Ecw

WOR L D W VID it

Conditional Statements in PHP

Figure 8.7 : Form Element Attributes

Sai(6'the file as 0erks.html under thejvar/www/htmi w--,/btzn3 "directory."

Open a new file in the text editor.

Enter the following code that retrieves values entered by the user in the PHP variables:

<HTML> <HEAD>

<TITLE> Grade Details</TITLE> </HEAD> <BODY>

<?php

$myn.ame=$—GET['myname']; $myg-rade=$—GET['mygrade'1;

7. Enter the following code to check whether the Name field is left blank:

if($myname=="")

id-4, 6dified

Page 97: Web Scripting With PHP 1-12

PrIECHWORLDWIDESessi n 8 Conditional Statements in PHP

Figure 8.8 : Case A

echo "Please enter your name"..;

Enter the following code after the if block to check whether th"rade field Is left bidblank: else

switch ($mygrade)

casecho. $inyname;

echo.* you id . break"-,--

odeW111-;~W.;::-**17111

n,

x e lan

ttpläy ac 044

6.1

Y,

F i l e E d i t V i e w a e a r c h T o o l s 2 o c u m e n t s H e l p

New Open Save Print Undo Redo Cut Copy -Paste Find Replace perks.htmlOx !.~. __ . .1 untitled 1* x I

case echo Smyname; echo ", you did not enter your Grade"; break;

case A: echo "Facilities for $myname (Grade A)"; echo "<BR><BR>"; echo "Increment = 30% of basic salary"; echo "<BR>"; echo "Bonus = 20% of basic salary"; echo 1. <BR> " ; echo "Travelling allowance = $SOO"; echo "<BR>"; echo "Medical allowance = $500"; echo " <BR> break;

. . . . . . . . Ln 43, Col. 36 INS

t F~l E

3

Scripting with PHP

Page 98: Web Scripting With PHP 1-12

AAVT,ECH-

Session 8 W,O R L D'W-1z0'.F

Conditional Statements in PHP

10. E rijfollowing code to display facilities for Grade B and Grade C:

case B: echo "Facilities for $myname (Grade B)"; echo "!5.BR><BR>"; echo "Increment = 20% of basic salary"; echo "<BR>"; echo "Bonus 10% of basic salary"; echo "<BR>"; echo "Travelling allowance = $300"; echo "<BR>"; echo "Medical allowance $300";echo "<BR>";

-1 break;

case:,echo;,

Facilities,~.5BR~;<BR.. U.I.-I, .~~-AMMem

v-..N e C ~ X14 "n r t e } r - e c W M - T 1 , n Off.

g allowance echo "<BR>"; echo "Medical allowance $100"; echo "<BR>"; break;

11. Enter the following code to check for any other values that a user enters in the Grade field:

default: echo "$myname, Please enter the correct Grade (A, B, or

C)"; break;

12. Enter the following code after completion of the PHP code to create a link that returns the user back to the main form:.

<BR><BR> <A HREF="perks.html"> Back </A> •/BODY> </!-ITML>

13. Save the file as calcPerks.php under the /var/www/htmj- directory.

14. Open the Mozilla Web browser.

Page 98 of 274 V 1.0 @ 2004 Aptech Limited Web Scripting with PHP

Page 99: Web Scripting With PHP 1-12

Session 8

(A—PrEcffWORLDWID

E

Conditional Statements in PHP

15. Type http://localhost/perke.html. key in the address bar and press the Enterkey. The form appears, as shown in Figure 8.9.

I'n X,File Edit View Go Bookmarks Tools Window Help

----------1 http:/Aocalhost/pe •••40 search C 4

Back Forward Reload stop L44 Print i : •, j Home *Bookmarks , e Red

Hat Network C j Support tElShop C , Pro t CITralnl d c s ng Please enter the information

CS

CI

Name: Enter your Grade (A/I3/C):

Submit

L . a ' L a i g a ( 0

Figure 8.9 : Grade-Facilities Form

Grade Details.- Mozilla BE1 file Edit View go -11ookmarks Tools Window Help

http://localhost/ca ivA-Search Back Forward Reload Stop ________ PrintMN

LI/Home I *Bookmarks 4*_Red Hat Network (1ISupport at Shop (:1'Products C:lTraining Please enter your name

Back

Done

Figure 8.10 : Message Prompting to Enter the Name

17. Enter John in the Name field.

18. Click the Submit button. The page appears, as shown in Figure 8.11.

Figure 8.11 : Message Prompting to Enter Grade

iliFile Edit View Go Bookmarks Tools Window Help

1 1 [ . 4 7 o c a l h o s Back Forward Reload Stop http://l t/calc E Search Print

:~15 Home 4 Bookmarks l#-Red Hat Network (:ISupport CtShop j:tProducts CI-Training

John, you d id not enter your Grade..

Back ack

ap [ Done

~- Scripting with PHP V 1.0 &:) 2004 Aptech Limited P a g e 9 9 o f 2 7 4

Page 100: Web Scripting With PHP 1-12

A P TIE CIA7

Session 8Conditional Statements in PHP

Click Back to return to the Information.html file.

20. Enter John in the Name field and enter A in the Grade field.

21. Click-Ahe Submit button. The facilities available for Grade A are displayed,asshown in. Figure #A

V G e ','Detal ~ c~zififia-,~---'~~, . . raiil lsz, M File Edit View Go Bookmarks Tools Window Help . .. ... ..

- a It [,4 http://localhost/calcP ;* Search Back Forward Reload Stop Print

I -It Home j Xf Bookmarks . R e d Hat Network (ISupport C,,ftShop C Products a:jtTraining Facilities for John (Grade A)

increment = 30% of basic salary

Bonus = 20%. of basic salary Travelling allowance = $500 Medical allowance = $500

Figure 8.12: Facilities for Grade A

8.3 Using. the Ternary Operator

Ternary operator is also known as conditional operator. It simplifies complex conditions into one line statements. Ternary operator is considered as a shortcut for if ... else statement.

We can modify the dispDet.php file to display the same messages using the ternary operator. To use the ternary operator.-

1. Open the dispDet.php file in the text editor.

2. Replace the PHP script in the code with the following script:.

<?php

$myname=$–P0ST[.'myname'1; $myage=$_POST['myage'l;

if ($myname=="") {

echo "Please enter your name";

else

$mOsg ($myage=="") ? $-.,rLyname, Please enter your age"

W0,R-Lic&,WA0M

Page 100 of 274 V 1.0 @ 2004 Aptech Limited Web Scripting with PHP

Page 101: Web Scripting With PHP 1-12

Conditional Statements in PHP

"Hi $myname. Your age is $myage";

echo $mesg;

echo $mesg;

PHP enters the; else'bl'ock:vVhen':th'~d.:"~','uset--dnt'ets W Name-,field.--'

Ing, a code, - ($1fi It checks whether. the Age field AiNleft blank.11ag AhL If the user has not entered the age l i *

,.-:the'-text-.after`the ? symbol is If then ."A 4' ~ 4 - V a e

user has entered the age, the messaoOHI-'$mynam-"e.~'You age trri" 9 :'Is didddl'

Save thq.,jOispDet.ph file ne ". M01, 1W 1- - — Operu,thej.Mozilla,.,',i dbTbfdWtdr-.

7. Click the Submit button. A. page appears, as shown in Figure 8.13.

V User, lnfarmadoit-Nozllll i File Edit View Go Bookmarks Tools Window Help

http://Iocalhost/dispC Search Back Forward Reload s t o p

Print !;} Home Bookmarks ** Red Hat Network (] jSupport jShop t: jProducts jTrainfnq

ED

John.

lieuk

LZ G 2 D o n e

Figure 8.13 : Message to Enter Age

.','eb Scripting with PHP

Page 102: Web Scripting With PHP 1-12

S e s s i o n 8

AWPFIECf-111, ,O'R'L W UD.E

Conditional Statements in PHP

IV File Edit View Go Bookmarks Tools Window Help

in . I ;AIIWIC~ "

I L vhttilocalhostidisp

Back Forward Reload Stop Search _______________ Print

k k d k d dHi John. Your age is 44

Back

91 G9 I Done

Figure 8.14 : Personal Details Displayed

Page 102 of 274

Page 103: Web Scripting With PHP 1-12

Session 8

(A—PTECHw o R L o w I o e

Conditional Statements in PHP

TRY IT YOURSELF

Part II - For the next half an hour:

1. Create a form for an online shopping mall that accepts details such as the customer name, the membership no., the type of membership, and the amount of points in hand. The two types of membership are Basic and Privileged.

3. Create a Job Application form for an organization that accepts the first name, last name, address, phone no., qualifications, and experience of the candidate. It must also display different department such as IT, Finance, and Sales for which the candidate wants to apply. Depending on the department selected, different posts that are available under that department must be displayed on the form. Use the switch statement-

V 1.0 ©2004 Aptech Limited

Points in Hand Additional Points Basic Member Privileged Member

Calculate and display the additional amount of points available and the total amount of points. Use if ... else statement.

I

-'. _: Scripting with PHP Page 103 of 274

Page 104: Web Scripting With PHP 1-12

Objectives

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

• Use Loops

Use Jump statements

Introduction

The loop statements control the flow of the statement execution. A loop executes a block of code repetitively- PHP provides us with the loop statements such as while loop, do-while loop, and for loop. The jump statements control the execution of the loop- The different types of jump statements are break, continue, and exi t.

In this chapter, we will learn how to use the various types of loop and jump statements.

9.1 'Working with Loops

A loop executes a block of code repetitively. In loops, the specified condition is tested and the statements in the loop are executed repetitively if the condition is true. If the condition is false, the loop ends and the control is passed to the statement following the loop. The continuous execution of statements placed inside the loop is called iteration.

PHP provides us with the following loop statements:

wh i l e Loop • do-whi-ie- Loop • for Loop

9.1.1,while Loop

A while loop executes the statements in the loop body as long as the condition is true.

The syntax for a while loop is:

while(condition)

Code executes if the cond.i.U'.orl is L.rue;Code execu tes i f the cond i t i on i s false;

,eb Scripting with PHP V 1.0 (e) 2004 Aptech Limited Page 105 of 274

Page 105: Web Scripting With PHP 1-12

A 0 r E c m .

Session 9 W,O-WL:*WjWR

Flow Control in PHP

The while keyword is followed by the condition in parentheses. The condition is the testexpression consisting of variables and operators. If the condition is satisfied, the code in the loopbody is executed. If the condition is false, the loop stops and the control move to the statementfollowing the loop.

Some examples of the while loop are:

To display the first ten multiples of 5:

<?php

$counter=l; $number=5; while($counter <= 10)

$result:=$number*$counter; echo "<BR>$result<BR>"; $counter=$couiiter+1; }

In the above code, the result is displayed until the counter reaches 10. The loop stops once the counter exceeds 10. To display the odd numbers between 1 and 10:

<?php

$number=j_; echo "The odd numbers ar-e:<BR><BR>"; wh_ilc($ni_2inber <= 10)

echo "<BR>$number<BR>"; $numbeY-=$nu1--,nbe)_-- 12;

In the above code, the number is always incremented by 2 until the number reaches 10.

9.1.2.-do-whilo.

In a while loop, the condition is evaluated at the beginning of the loop. If the condition is false,the statements in the loop body are not executed at all.

I f we want to execute the loop body at least once, we must use the do—vihile loop. Thedo—whl-lo loop works similar to the -while loop. The only difference between the while anddo-while loop is that in the do-while loop, the condition is placed at the end of the loop.

Page 106 of 274 V 1.0 C 2004 Aptech Limited Web Scripting with PHP

Page 106: Web Scripting With PHP 1-12

Session 9 Flow Control in PHP

The syntax for a do-while loop is:

do

Code executes if the condition is true; }

whil.e(cond-ition); Code executes i f '

: the condition is false;

In do—while loop, the loop body follows the do keyword. The loop body is executed at least once.The loop body is followed by the while keyword and the condit ion in the parenthesis. If thecondition returns true value, the loop executes. If the condition returns false value, the loop ends

p and the statements following the w-hi -- e keyword are executed.

Some of the examples of d o loop are:

To display the odd numbers between 1 and 10:

<?php $number=l; echo "The odd numbers are:<BR><BR>"; do

echo "<3R>$numbci--<BR->"; $num1Der=$number+2;

10) echo "<BR>Th(-- value cool-d not- be dis-piayed";

The above code displays the odd numbers between 1 and 10 using the do-while loop. Before the iteration of the loop starts, the value is displayed once. Then the execution starts.The value keeps displaying until the counter reaches 10. The loop stops once the conditionis satisfied.

To print the even numbers up to 10:

<. P--1P

$cc)ljj-ltej,--O; echo "The even numbers ar'e: <BR><BR>" do

echo co u ri t. -- 17,-, B P.::-

" 'c o " 1 1- T --r= Scot..- ze-r'!

r I I coul-aL-ef< =

< 3 RD•- T h e v a 1. 1- 1 e could not b e displayed";

f i e f S c r i p tin g w i t h P H P V 1.0 ' e ) 2004 Aptech Limited Page 107 of 274

Page 107: Web Scripting With PHP 1-12

Session 9 Z . L

Flow Control in PHP

The above code displays the even numbers using the do-while loop. Before the iteration ofthe loop starts, the value is displayed once. Then the execution starts. The value keepsdisplaying until the counter reaches 10. The loop stops once the condition is satisfied.

v1'1̀_11-1~1._ P O P .

A for loop enables us to execute a block of code repetitively for a fixed number of times. Theloop executing statements keeps executing until the testing condition gets satisfied. Once thecondition gets satisfied, the loop stops executing.

The syntax for the tor loop is:

f or (in iti. a l iz at". on; condition; re-initializaL.-ion)

Code executes If the condition is true; }

Code executes if the condition is false;

The for loop consists of initialization expression, text expression and re-initialization expression.The condition expression specifies the test expression. The initialization expression initializes thevalue of the counter. The re-initialization expression increments or decrements the counter. Thecode inside the loop is executed only when the condition returns true value. The re-initializationexpression helps in the iteration of the loop.

Some of the examples for the for loop are:

> To display the output of the multiplication of a number by 2:

< ?PIMP

$num.ber=6; for ($counter=1.; $coijnt.-.or <= 6; $count.er++-) i

echo < B R > $ nu- n i b e r <113R, R $numbe,.r = -: riUmbe r * 2

echo "Values could not be calculated.";

In the above code, the for loop is used to display the double of the number. The loopexecutes until the counter value reaches to 6. Once the counter value reaches 6, the loopstops executing.

To display the first five odd numbers in the reverse order:

< ?,,.-)hp

echo• "The odd numbers arc-, for $i>=i;

Page 108 of 274 V 1.0 C-) 2004 Aptech Limited Wet) Scripting with PHP

Page 108: Web Scripting With PHP 1-12

Session 9 Flow Control in PHP

$ n u n a b e_ r = $. ; L . * 2

echo $riumber;

e c h o " V a l u e s c o u l d n o t b e c a i - c - u l a t - e d . " ;

In the above code, note the for loop contains the counter, which is initialized at 5. The re-initialization expression decrements the counter every time the for loop is executed.

atement

• jump statements control the execution of the loop statements. PHP provides the following jump statements:

> break statement > cont.inue statement > exit statement

92.1 break Statement

The ',--)rea.k statement stops the execution of the loop. The control is then passed either to thebeginning of the next loop or to the statement following the loop. This statement can be used withthe i f statement, staternent, f o r loop, loop, and (3o-wh i le loop.

Some of the examples for the break statement are:

To display the consecutive numbers from 1 to 10:

<?P11P

i f ($ i . > 10)

break; I ecYio

In the above code. the statement is used with the vo r loop. The condition isspecified in the t statement. The statement controls the loop. If the ' O r r a k statementis not used, then the loop will go in continuous state.

_-'ping with PHP V 1.0 200_,l Aptech Limited Page 109 of 274

Page 109: Web Scripting With PHP 1-12

Session 9 A P carsV

Flow Control in PHP

To check whether the alphabet is a vowel using s-vji.t.-.ch statement:

?php

$a.ioI1aj_-,eL='u' ; switch ($alphabet)

case 'a': echo "<bR><BR>The alphabet is a vowel. break;

case 'A': echo "<BR><BR>The alphabet is a vowel. break;

case echo "<BR><BR>The alphabet is a vowel. break;

case 'E': echo "<BR><BR>The alphabet is a vowel."; break;

case

echo '<BR><BR>Thc alphabet is a vowel.."; break;

case 'I': echo "<BR><BR>The alphabet is a vowel. bf c. ak;

case , (-), : echo "<BR><BR,>The al,:)habet, IS a vowel. break;

case '0'. echo "<BR><BR>The alphabet is a vowel. break;

case u'. echo "<BR><BR>The- alphabet is a vowel. break;

case echo =:i31 alphabet is a vowel break;

default:

Page 110 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Page 110: Web Scripting With PHP 1-12

Session 9 WO K;L 0 . "OV

Flow Control in PHP

echo "<r--?—BR>Tno alphabet is not a vowel.";

In the above code, the break statement is used in the switch statement. The breakstatement moves the control to the statements following the st^.-,Itch statement. If thebreak statement is not used, PHP executes all the statements including the statements ofthe following cases in the switch statement.

9.2.2 continue Statement

The continue statement is used with the loop statements. It skips the code following thecontinue statement in the loop body and forcibly executes the next iteration of the loop. Thisstatement is normally used in the nested loops. The continue statement can be used with the ifstatement, for loop, chile loop, and do-while loop.

For example, to display the consecutive numbers from 1 to 10 using the while loop:

<?php $counter = 0; while($counter<10) f

$counter++; 4 —'L($counter==5) f

echo "Continues the loop" continue;

I echo "$counter<BR><BR>";

echo "The loop ends here";

In the above code, the continue statement is used in the it statement. Here, the counter isinitialized to 0. The loop continues until the counter reaches 5. As the counter increments to 5,the loop skips the if body and executes the next iteration of the loop. The loop continues until thecondition becomes false.

9.2.3 exit Statement.

The exit statement ends the loop and the control is passed to the statement following the loop body.

- Scripting with PHP V 1.0 ((~` 2004 Aptech Limited Page 111 of 274

Page 111: Web Scripting With PHP 1-12

Session 9

Flow Control in PHP

For example, to calculate the HRA:

<?P11P s s a l a r y = 80 0 0 ; if($salary<6000)

echo "Basic : $salary,--BR><BR>"; echo "Ertiplovees having salary below, 6000 are not entitled to receive HRA.

exit;

} else

echo "Basic $ sa la ry---BR><Da>" $hra=$salary 0.2; echo "HRA $hra"; }

In the above code, HRA is calculated based on the basic salary. If the basic salary is less than 6000, the if statement exits. If the basic salary is greater than or equal to 6000, HRA is calculated.

Page 112 of 274 V 1.0 ((.: 2004 Aptech Limited Web Scripting with PHP

Page 112: Web Scripting With PHP 1-12

A r- 2rEcmSession 9 ORIL'O WI D F

Flow Control in PHP

> A loop executes a block of code repetitively.

A while loop executes the statements in the loop body as long as the condition is true.

> The do-whil I e loop works similar to the while loop. The only difference between the whi l e a n d l oo p i s t ha t i n t h e do-wh i l e l o o p , t he c on d i t i o n i s p l ac e d a t t he end of the loop.

A for loop enables us to execute a block of code repetitively for a fixed number of times.

The jump statements control the execution of the loop statements.

.1 10, The break statement stops the execution of the loop. The control is then passed either

to the beginning of the next loop or to the statement following the loop.

> The continue statement skips the code following the continue statement in the loop body and forcibly executes the next iteration of the loop.

The exiL statement ends the loop and the control is passed to the statement following

the loop body.

I scripting With PHP V 1.0 t, 2004 Apte0i Limited Page 113 of 274

Page 113: Web Scripting With PHP 1-12

Session 9 Flow Control in PHP

1. The ___________ statement executes a set of code only when a condition is true.

a. If

b. Switch

C . Conditional

d . while

2. In the _____________ loop, the condition is placed at the end of the loop.

a. while

b. do-while

C. for

3. A ______________ loop enables us to execute a block of code repetitively for a fixed number of times.

a. for

b. while

c . do-while

d. for -each

4. The ___________ statements control the execution of the loop statements.

a. conditional

b. jump

C. loop

5. The statement stops the execution of the loop.

a. continue

C. exitloop

C. break .... ... ...

Page 114 of 274 V 1.0 © 2004 Aptech Limited Wet) Scripting with PHP

Page 114: Web Scripting With PHP 1-12

Objectives

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

Use the rah j 1 e loop

Use the do-w1211r loop

Use the for loop

Use the'u.% .7 4) statement

The steps given in the session are detailed, comprehensive and carefully thought through. This. has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully.

Part I - For the first 1.5 Hours:

10.1 Using the while Lo 3 0ap-I

A while loop executes the statements in the loop body as long as the condition is true.

We will generate the Fibonacci series using the while loop.

1. Open the gedit text editor.

2. Enter the following code for displaying the Fibonacci series:

<?php $fibl=0; $fib2=1; echo "The fibonacci series <BR><BR>"; echo "$fibl<BR>"; while($sum<15) {

echo "$fib2<BR>"; $sum=$fibI+$fib2; $fibl=$fib2; $fib2=$sum;

echo "<BR>"; return 0;

3. Save the file as fibo.php under the /var/www/html directory.

Scripting with PHP V 1.0 Cc.) 2004 Aptech Limited Page 115 of 274

Page 115: Web Scripting With PHP 1-12

Session 10 CrECAI Flow Control in PHP

4. Open the Mozilla Web browser.

5. Type http: //Iocalhost/fibo.php in the address bar and press the Enter key. The Fibonacci series appears, as shown in Figure 10.1.

n rX File Edit View Go Bookmarks Tools, Window Help

3 .?,t litip:[Aocalhostj search! For Reload [ _____ E

/,IHome 'Bookmarks .4-P Red Hat Network C 'Supporl-'sliop -'Products -'Training

i j j

The Fibonacci series :

1

5

13

e-9) Done

Figure 10.1 : Viewing the Fibonacci Series

10.2'.Ut sing The do-*hi3.e loop..,

The do-while loop works similar to the while loop. The only difference between the `,-chile and do--c~.71-iile loop is that in the loop, the condition is placed at the end of the loop.

For example, to display the first ten odd numbers in the reverse order using the do-while loop:

iwt

1. Open the gedit text editor.

2. Enter the following code to display the first ten odd numbers in the reverse order:

<?php echo "Odd numbers in reverse order:<BR>"; $i=10; do

$num=$i*2-1; echo "<BR>$num";

}while (S J >=I )

I Save the file as odd.php under the /var/www/html directory

4. Open the Mozilla Web browser.

Page 116 of 274 V 1.0 (F-D 2004 Aptech Limited Web Scripting with PHP

Page 116: Web Scripting With PHP 1-12

Session 10

Aprr1r.Iff I.T.

Flow Control in PHP

5. Type http://localhoi3t/odd.php in the address bar and press the Enter key. The output appears, as shown in Figure 10.2.

Figure 10.2 : Viewing Odd Numbers in Reverse Order

10.3 Using the-for Loop

A for loop enables us to execute a block of code repetitively for a fixed number of times. The for loop consist of the initialization expression, test expression, and the re-initialization expression.

For example, to display the square of the first ten numbers using the for loop'.

1. Open the gedit text editor.

2. Enter the following code:

< ?phT-)

echo "The square of -first. ten numbers are :<BR><BR>"; for ($i=1;$i.<=10;$-i-j-+) r I

$ square= $ i * $.i. ; echo "$i X $i = $square"; echo "<BR>";

3. Save the file as square.php under the /var/www/html directory. .

Open the Mozilla Web browser.

6z

File Edit View Go Bookmarks Tools Window Help 3 Search crop IDS d Fl~ 1,e,,— 1

Back Reload s opi I . at - p:lfioc . alh ---- Print ;i Home 'Bookmarks -**-Red Hat Ner"rk ,-j'Support t:Shop -'Products "Training j"Training

Odd M111111CI-I in rr r r wder:

19 17 15

Il 9 7 5 3

i Z \ Z I Q G 1 D o n

V

Web Scripting with PHP V 1.0 200-1 Aptech Limited P a g e 1 1 7 o f 2 7 , 1 1

Page 117: Web Scripting With PHP 1-12

pa-

Session 10 Flow Control in PHP

5. Type http://localhost/square.php in the address bar and press the Enter key. The output appears, as shown in Figure 10.3.

175: X

File Edit View Go Bookmarks Tools Window Help 7 .. . ......... ..

http://localhost/sq Back F omard Reload Stop E

.................... ... . .... ...... --- -- -

J Home ',JBookmarks 4–

tRed Hat Network Support (!!shop _J

Pnnt -'TrainingLJ

4~k_ Search

-'Products L-3

1-he square of first ten numbers

arc

I X 1 1 2 X 2 A

;X; = 9 4 x 4 - 1 6 5 X 5 2 5 6 X 6 = 36 7 X 7 = 4 9 8X8=0-4 9X9=81 l o x 1 0 100

C - 4 3 < 2 2 Done

Figure 10.3 : Displaying the Square of the First Ten Numbers

Wp.04 MIA the.- JumpStatements . 2 g P S e

The jump statements control the execution of the loop statements. The various jump statements are break statement, continue statement, and exit statement.

The break statement stops the execution of the current loop and the control moves to the nextloop. The con .tinue statement skips the code following the continue statement in the loopbody and forcibly executes the next iteration of the loop. The exit statement ends the loop andthe control is passed to the statement following the loop body. These statements are used in the ifstatement, for loop, while loop, and do-while loop.

To display the inverse of a number:

1. Open the gedit text editor.

2. Enter the following code to create a form for accepting a number:

<HTML> I

<BODY> <FORM METHOD "GET" ACTION "breakinv.php"> Enter number: <INPUT TYPE "TEXT" NAME = "num"-

Page 118 of 274 V 1.0 @ 2004 Aptech Limited Web Scripting with PHF

Page 118: Web Scripting With PHP 1-12

Session 10

WORLDWIDE

Flow Control in PHP

<BR><BR><INPUT TYPE = "SUBMIT" NAME = "submit" VALUE = "INVERSE"> </FORM> </BODY> BODY> </HTML>

3. Save the file as break.html under the /var/www/html directory.

4. Open a new file in the text editor.

5. Enter the following code to display the inverse of the number:

< ? p h p $number=$_GET['num'1;

if($number==0) f exit;

echo "<BR><BR>Inverse of the number is 1/$number"; echo "<BR><BR><a href=break'-html>Go Back</a>";

6. Save the file as breakinv.php under the /var/www/htmi directory.

7. Open the Mozilla Web browser.

8. Type http: / / localhost /break. ht:ml in the address bar and press the Enter - key. The form appears, as shown in Figure 10.4.

Figure 10.4 : Displaying the Form

A41rW1W_0*9*WA_~AWj WIAM-9 -

F i l e E d i t V i e w G o B o o k m a r k s T o o l s W i n d o w H e l p

http:/jloc afhost.lbieak. fit nie r~h Print

13 Home j Bookmarks Red Hat Network ~Supfport -'Shop -'Products j j j Training

I =mcr nu whet: i

INVERSE

Done

4 Back Reload

e:, Scripting with PHP V 1.0 © 2004 Aplech Limited Page 119 of 274

Page 119: Web Scripting With PHP 1-12

Session 10 Flow Control in PHP

9. Enter the number as -7.

10. Click the INVERSE button. The page appears, as shown in Figure 10.5.

XM6

File . . ... ........

Back

Edit View----------

For ard

Go Bookmarks7--.7 . .. ....

............

Reload

Tools Window Help

Hi

4 http:/Pocalhos reakinv.r _;A-. Search Print Nrr

— r ' 9L i

, J r n H o e j B o o k m a r k s - 0# Red Ha t Ne twork ' J S U P P O r t ` j

Inverse. ofthe number is U-7

Go Back

-- 4 & E 5 \ 4 ' C 7 < 0 D o n e

Figure 10.5 : Displaying the Inverse Number

12. Click the Go Back hyperlink.

13. Enter 0 in the text box and click INVERSE. Note a blank screen is displayed.

Page 120 of 274 V 1.0 ((,) 2004 Aptech 1-ignited Web Scripting with PHP

Page 120: Web Scripting With PHP 1-12

Sess~oirll 10

(A'PF,EC,NWORLDWIDE

Flow Control in PHP

TRY IT YOURSELF

Part II - For the next half an hour:

1 1. Write a program to display cube of the first 10 numbers.

2. Write a program to check whether the user is an adult by accepting the age of the user.

- : -'pting with PHP

Page 121: Web Scripting With PHP 1-12

Session 11 ( A — P y w c w

woe L-D W IV E

Functions in PHP

11.2 Built-in PHP

PHP provides us with some built-in functions. We can categories these built-in functions into:

Mathematical functions String functions Date and time functions Error handling functions Database functions Array functions Mail functions

Built-in functions are placed in the PHP script.

11.2.1 Mathematical F ti

Mathematical functions operate on numerical data. Table 11.1 lists and describes some of the mathematical functions:

Table 11.1 : Mathematical Functions

Some of the examples for the mathematical functions are:

To find the nearest integer of the number, 99.6: < ? ~ ' 3 1 1 0

echo "The nearest integer o--F 99.6 is: echoI round(99.6);

Note the above code will return 100 as the nearest integer.

11 ;

Function Name Syntax Description

Page 122: Web Scripting With PHP 1-12

A Sessi n 11 (A—PrECH

\ !!O~R LDWIDE

To find the largest of the arguments:

<?php echo "The largest number from 99.9, 9.9999, and 99.99 is: echomax(99.9,9.9999,99.99);

Note the above code will return 99.99 as the largest value.

To find the square root of the number, 256:

<?php echo "The square root of 256 is: echo sqrt(256);

Note the above code will return 16.

11.2.2 String Functions

String functions operate on character type of data. Table 11.2 lists and describes some of the string functions:

Table 11.2 String Functions

nb Scripting with PHP V 1 . 0 U 2 0 0 Ap t e ch L im i t ed Functions in PHP

Page 123: Web Scripting With PHP 1-12

Session 11(A_PY',ECAf

WORLD W1-DE

Functions in PHP

Some of the examples for the string functions are:

To find the length of the string, HELLO:

< ? p h p

echo "The length of the string HELLO. is:" echo strlen(HELLO);

Note the above code will return 5.

To convert a string to the lower case:

<?php echo strtolower(PHP);

Note the above code will display PHP in the lower case.

To find the ASCII equivalent of the letter, A:

<?php echo bin2hex(A);

Note the above code displays 41.

11.2.3 ANWIn Im'eAnctions 1.2.3 B d T!

The date and time functions enable us to find the date and time on the system. Table 11.3 lists and describes some of the date and time functions:

Table 11.3 : Date and Time Functions

Page 126 of 274 V 1.0 © 2004 Aptech Limited

Web Scripting with PHP F u nc t i o

Page 124: Web Scripting With PHP 1-12

Sessi•n 11

(A—PYWCH = L - O W I D e

Functions in PHP

Some of the examples of using the date and time functions are:

`r To obtain the day:

<?php echo date("l");

Note in the above code the "I" is the argument string, which corresponds to the textual representation of the day of the week. Above function will return the day-

To display the current month:

<?php $A=getdateo; $month=$A['month']; echo $month;

Note the above code will return the current month.

11.2.4 Error Ha dam, Functions

Error handling is the process of dealing with errors as they arise during the run-time. PHP provides us with the error handling functions to define the error handling rules. Table 11.4 lists and describes some of the error handling functions:

F u n c t io n

(error_msg

t r i g g e r _e r r o r

t r i g g

s e t — e r r or — h a n d i e

( e r r o r — r ep o r t i n g Constant) PHP provides many

levels of errors_ We can use this function to set a level

d ring the r n time of the script T able 1 1 . 4 Er ro r H a nd l i ng Fu nc t i o ns

Scripting with PHP V 1.0 OL 2004 Aptech Li cited Page 127 of 274

Page 125: Web Scripting With PHP 1-12

I ( " a F r a n

!oR. L D W I-WE Sess~on I Functions in PHP

The error_reportingo function requires constants as arguments. Table 11.5 lists and describes some of the error constants:

Table 11.5 : Error Constants

Some of the examples for the error handling functions are:

To report only the simple errors that are running:

<?ph-,)

$A=error—reporing(E—ERRORIE—WARNINGIE_P,ARSE); echo $A;

Note the above code displays the errors depending on the constants used as arguments.

To generate a user-defined error:

<?php $num1=0; if(num1==0)

trigger—error("Cannot divide by zero", E_USLR_ERR0R);

else

$B=100/rIUMI;

Note in the above code the value of $nurnl variable is tested. Since the value of snuini is equal to zero the code in the if body is executed.

Constant Name Description

Page 126: Web Scripting With PHP 1-12

Session 11

(.-4PT,ECJVWORLDWIDE

Functions in PHP

11.3 User-d FunctionsUser-dined Fu

A user can also define a function. A function has to be defined before it is used. The function definition contains the code for the function.

The syntax to define a function is:

Z _ . ~ -fun name( f_nction

code

The function keyword is followed by the function name. In the above syntax,

> fun–name - Specifies the name of the function

> code – Specifies the body of the function

To execute the function, we have to call the function.

Tine syntax to call a function is:

- -n–nameo;

Where fun nameis the name of the function

Some of the examples for creating a function are:

> To create a function that calculate the sum of two variables, enter the following code:

<?php

function addition()

$A=100; $3=200; $C=$A+$B; echo "The sum of 100 and 200 is. $C";

addition(};

Note in the above code the addition( ) function adds the variables $A and $B and stores the value in $c.

Page 129 of 274

~~-ipting with PHP V 1.0 © 2004 Aptech Limited

Page 127: Web Scripting With PHP 1-12

Session 11CA-10TECHORLDWIDE -

Functions in PHP

To create a function that displays the text, enter the following code:

<?php function Display()

echo "LEARNING PHP IS FUN";

Display();

Note in the above code when the Display() function is called, the sentence is displayed.

11.4 Passing Arguments to Functions

Sometimes it is required that we have to accept inputs from the user. These inputs are processed for producing the desired output. For such cases, we can also design complex functions that accept inputs from user. These inputs that are passed to the functions are termed as arguments. A function can be designed to accept multiple arguments.

The syntax to define a function with arguments:

function fun_name(argl,arg2,...)

code }

Where,

arg - Specifies the argument that is passed to the function

There are three ways in which the arguments can be passed to the function. They are:

• Passing arguments by value Passing arguments by reference

>- Setting default value for arguments

11.4.1 Passing Arguments By

When the argument is passed by value, the value of the argument remains unchanged outside the function. The arguments are prefixed with the dollar ($) sign in the function definition to indicate that the argument will be passed by the value.

V 1.0 ©2004 Aptech Limited Web Scripting with PHP Page 130 of 274

Page 128: Web Scripting With PHP 1-12

Session I I

V 1.0 (q) 2004 Aptech Limited Page 131 of 274

rEcIff DWI'DE

Some of examples of passing the argument by value are:

To create a function for calculating the square of a number, enter the following code:

<?php function Square($A)

$A=$A*$A; echo $A; }

$A=5; echo "The square of $A is: Square($A);

Note in the above code, we have passed the argument by value_ The variable $A is passed to the Square ( ) function, which multiplies $A with $A and stores the resultant in the same variable. The output displayed is 25.

Now when we display the value of $A outside the function,5 is displayed instead of 25. This is because the execution of function does not affect the value of the variable outside the function.

To create a function that subtracts one variable from another, enter the following code:

<?PhP function subtraction($A,$B)

$C=$A-.$B; echo " The difference of $A and qB is: $C";

s u b t rac tL- i on (9 0, 4 5)

Note in the above code, we pass two arguments to the function subtraction() -The subtraction ( ) function subtracts the variable $B from $A and stores the value in $c.

11.4.2 Passing Argument By Reference

We can also pass the argument by-,reference. If we pass the value by reference, the value is modified even outside the function. When a function is defined, arguments must be prefixed with the ampersand (&) sign to indicate that the value is passed by reference.

-3b Scripting with PHP

Page 129: Web Scripting With PHP 1-12

I —ARTECIff

Session W O R L O W 4 0 - - E

Functions in PHP

Some of examples of passing the arguments by reference are:

To create a function for calculating the square of a number, enter the following code:

<?php function Square(&$A)

$A-.$A*$A; echo $A;

$A=5; echo "The square of $A is: Square($A);

Note in the above code, we have passed the argument by reference. The variable $A is passed to the square ( ) function, it multiplies $A with $A and stores the resultant in I the same variable. The output displayed is 25.

Now when we display the value of $A outside the function, the output will be 25. This is because the execution of function changes the value of the variable even outside the function.

To create a function that calculates the product of two variables, enter the following code:

<?php function multinlication(&$A,&$B)

$C=$A*$B; echo "The multi plication of $A and $B is. $C"; }

$A=25; $B=30; multiplication(SA,$B);

Note in the above code, we pass two arguments to the function multiplication H.The mul ti-ol. ication function calculates the product of two variable $A and $B and stores the value in sc.

11.4.3 Setting Default Values

We can also assign default values to the arguments. We must assign a default value to the argument in the function definition. Now, even if the user tries to pass different arguments, the function would process only the default value.

Page 132 of 274 V 1.0 Oc 2004 Aptech Limited Web Scripting with PHP

Page 130: Web Scripting With PHP 1-12

Session 11

AAPFECH 0 R L.D. W I -DAr

Functions in PHP

For example, to create a TA function for calculating the traveling allowance based on the basic salary:

<?Php :unction TA($BASIC_SAL=10000). { STA=0.25*$BASIC_SAL; echo "The TA is: $TA"; } TAO;

Note in the above code, the TA ( ) function calculates and displays the traveling allowance. It calculates the traveling allowance at the rate of 25% on the basic salary.

11.4.4 Returning. Values from Functions

A function can also return values. The return statement returns the value from the function.

For example, to create a HRA ( ) function for calculating the house rent allowance:

<?php f u n c t i o n H R A ( $ B a s i c _ S a l )

$11RA=0.25*$Bas_Jc_Sa1; return $HRA;

SBasic—Sa1=20000; SB=11RA e c h o $ B ;

Note in the above code, the HRA ) function returns the house rent allowance, calculated at the rate of 25% of basic salary. The return $HF-A statement returns the HRA. The above code returns 5000.

111.4 .5 Nesting of Funct ions

We may use several functions in a program. These functions may be dependent on few other functions defined in the program. As.a result, a function may require calling other functions. When one function calls another function, it is termed as nesting of functions.

V ILO 2004 Aptech Limited Page 133 of 274

Scripting with PHP

Page 131: Web Scripting With PHP 1-12

Session 11 WfOAMMM48M.

Functions in PHP

For example, we will define a function named Net–Salary (), which in turn calls functions, such as HRA () , TAX() , and DA(). .

<?php $Ba.sic—Sa.1=20000,- function HRA($Basic_Sal)

$HRA=0.3*$Basic_Sal; return $HRA;

function TA($Basic_Sal)

$TA=0.25*$Basic_Sal; return $TA;

function TAX($Basic_Sal)

.$HRA=0.1*$Basic_Sal; return $TAX;

function Net_Salary($Basic_Sal)

$A=HRA($Basic_Sal); $B=TA($Basic—Sal); $C=TAX($Ba.sic_Sal); SNet—Sal=$Basic_Sal+$Ai-$B-$C;

echo "Your Net Salary is: echo $-Net—Sal;

Net_Salary($Basic_Sal);

Note in the above code the Net_ O function calls three functions, HR.=. () , T ( ) , anc TAX ( ) . The Net—Salary function calculates the net salary using the values returned by the three functions_

Recursio

Wehave seen that one function can call another function. Also a function can call itself. Whea function calls itself several times, the process is termed as recursion. When a function calls itself the same code is repeated. For example, we can use recursive functions in programs tc calculate the factorial and Fibonacci series.

Page 134 of 274 V 1.0 Q 2004 Aptech Limited Web Scripting with P--

Page 132: Web Scripting With PHP 1-12

Session 11 Ei-Pr'ECITOAR L DM 1 0

R

Functions in PHP

For example, to use a recursive function for calculating the factorial of a number:

< ? nho $A=4- function factorial($A)

return 1; I else

return $A*factorial($A-1);

echo "The factorial is:. $B=factor-ial($A);

echo $B;

In the above code, the factorial() function returns 1 if the input is 0 or 1. Otherwise the factorial () function will call itself to calculate the factorial. Above function will return 24.

We can also use non recursive function instead of recursive function in the above factorial example. In a non recursive function we have to use a loop instead of recursion. There are instances where a recursive function is simpler to code than a non recursive function. The code written by using the recursive function is easier to understand. The recursive functions also have the disadvantage that they sometimes require more time to execute as against the non recursive function.

eb Scripting with PHP V 1.0 C 2004 Aptech Limited Page 135 of 274

Page 133: Web Scripting With PHP 1-12

A 0 FIECH

Session 11 WO R-LO W 10 E

Functions in PHP

Functions are used to avoid rewriting the codes again and again.

i We have built-in functions in PHP. The built-in functions can be categorized as: I

• Mathematical Functions

∗ String Functions

• Date and Time Functions

Error Handling Functions

∗ Database functions

Array functions

∗ Mail functions

Mathematical functions operate on numerical data.

String functions operate on character type of data.

Date and time functions enable us to find the date and time on the system.

I Error handling functions enables to define the error handling rules

We can also define a function.

We can pass arguments to a function.

We can pass arguments to a function by value, reference, or even pass default values to a function.

Recursive functions calls it self. - )~-

Recursive functions are simpler to code-

Page 136 of 274 V 1.0 (0 2004 Aptech Limited Web Scripting with M'

Page 134: Web Scripting With PHP 1-12

A p r E c m

c 3 e s s i o n WORLDWIDE

Functions in PHP

CHECK YOUR PROGRESS

1. A function name can contain ___________

a. periods

b. underscore

C. blank spaces

d. reserved keywords

The ___________ function returns the ASCII value of the first character of the string.

a. chr ()

b. bin2 hex

C. ord

3. The time() function provides the time in number of

a. hours b. minutes

C. seconds

4. The trigger_error () function _______________________

a. generates an user error

b. generates the PHP back trace

C. sets a user function to handle errors in script

5. When we pass the arguments by value, the arguments value

a. remains unchanged outside the function

b. changes outside the function

C. remains constant inside the function

6. We use the sign to pass the arguments by reference to the

a.--ec Scripting with PHP V 1.0 (0 2004 Aptech Limited Page 137 of 274

Page 135: Web Scripting With PHP 1-12

A P.MCK

Session 11 WOIM'D-,WI'DIE

Functions in PHP

a. one function calling another function several times

b. a function calling itself number of times

C. two functions calling the same function

Recursion is

t

Page 138 of 274 V 1.0 Oc 2004 Aptech Limited Web Scripting with PHP

Page 136: Web Scripting With PHP 1-12

Objectives

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

Use the built- in functions

• Create the user- defined function

> Pass arguments to a function

Return values from a function

The steps given in the session are detailed, comprehensive and carefully thought through. This has been done so that the learning objectives are met and the understanding of the tool is complete. Please follow the steps carefully.

Part I - For the first 1.5 Hours:

~ n g W - 0 I F U n a t o n s 1 2 . 1 U P s r n , ' - A d M a f l f f l e % a t

PHP provides built-in mathematical functions that operate on numerical data. For example, to accept a number and display the square root of the number using the PHP script:

1. Open the gedit text editor.

2. Enter the following code to create a form that accepts a number:

<HTML> <BODY>

<FORM M E T H O D = G E T ACTION "Squareroot.php"> Enter a Number: <INPUT TYPE="TEXT" NAME="n1text"> <BR> <BR>

<INPUT TYPE="SUBMIT" NAME = "SQUARE ROOT" VALUE=". - $QUARE ROOT"> </BODY> </HTML>

3. ..Save the file as Squareroot.htmi under the /var/www/htmi directory.

4. Open a new file in the text editor.

,%eb Scripting witi, PHP V 1 . 0 C c) 2004 Aptech Limited Page 139 of 274

Page 137: Web Scripting With PHP 1-12

I

(A—PrECRINOR LOWIDE

S e s s i o n 1 2

7'g:*- 46 foilow'Wng code to find the square root of a number:

L75 "';' P-4) (3g I Done

Figure 12.1 : Square Root Form

9. Enter 64 in the Number text box.

10. Click the SQUARE ROOT button. The output appears, as shown in Figure 12.2. in I'X

File Edit Viewookmarks Tools Window Help 9jo P

. 1 L ~~n~.JflocalhosV.J~j & * S . r c h l . 2 Back Fon%ard Reload Stop Print -

Home o V4Bookmarks 4#- Red Hat Network 2tiSupport

L-'jShop Products EjTrainnq The square row of 64 is: 8

....... . ... . (021 1'Done - ----- ----

Figure 12.2 : Viewing the Square Root

:',',GET n1text p , ,_square . roo t of § ; A i s : f f ;

qrt ($A) ;

le -'. file ~, ef iivareroot-PbP under-4he /var/www/htmi; I directoryA b3Mo'zllla,-,-Web browser. -

XY pai3liolist/iiqu ot'' htaL im,'Jponn , ppeqrp hsNsbdWn I n

E 19 Je; nn':514

mozlula

V 1.0 Oc 2004 Aptech Limited

.Wlklwl~x

4 http:/P(

Enter a Number: I

SQUARE ROOT I

Page 140 of 274

Page 138: Web Scripting With PHP 1-12

Session 12

APrEcivWORLDWIDE

Functions in PHP

12.2 Using the String -Functions

PHP provides string functions that operate on character data. For example, to obtain the ASCII equivalent of B using the PHP script:

1. Open a ri ille,01he 46xt e4k

3. Enter the following cod&i:,' < ?php

71 A-~., 40qWM

13

Figure 12.3 : Displaying Hexadecimal Equivalent

12.3 Using the' Date ' and Time, Functions

The date and time functions in PHP enable us to retrieve the date and time on the system.

Scripting with PHP

V 1.0 © 2004 Aptech Limi ted Page 141 of 274 !i f MOZ111a Edit 'Vi ' B k i

Page 139: Web Scripting With PHP 1-12

(A-PrEavWORLDWIDE

Sessi n 12

For example, to display the current time in seconds using PHP script: code

Mao, TOW 0 4

1087570279

Done -------- --

. .............

Figure 12.4 : Displaying Time in Seconds

12:4 Crest .tjp the:

addition to the built-in functions, the user can also define their own functions to perform tasks.

For example, to create a function that calculates the remainder:

1. Open a new file in the text editor. 2. Enter the following code:

Functions in PHP <?php

function? V 1.0 ©2004 Aptech Limited Web Scripting with PHP

Page 142 of 274

Page 140: Web Scripting With PHP 1-12

S . e s s i o n 1 2

A p r E C H

0O~ RLDWIDE

Functions in PHP

nio a

~eoutputappears !a

4 http./fiocalh

Florney6dokmarks

The remainder is 5

- 0 4 ( E R D o n e . . . . . . . . . . . . - ------------ Figure 12.5 : Displaying the Remainder

12.5 Passing Argument to a Fu.nct!Qh by. Value.

When we pass the argument to a function by value, the value of the variable is modified only inside the function. The change in the value of the variable is not reflected outside the function.

For example, to accept two numbers and display their product using a function:

1. Open a new file in the text editor.

2. Enter the following code to create a form that accepts two numbers:

<HTML> <BODY>

I ~ z S c r i p t i n g w i t h P H P V 1.0 © 2004 Aptech Limited

Page 141: Web Scripting With PHP 1-12

Session 12Functions in PHP

ENTER THE FIRST NUMBER: < INPUT TXPE= " TEXT" NAME= "numl text " >

R -

5. Save the file as

07MMultipl Pbpu

W/htMl directory.,

rowser. show

.

in

Flle Edit View Go 'Alookmarks Tools

Back Forward Reload Stop ____________ aa Search Print .1 Home Y4Bookmarks ,Red Hat Network EtSupport (iŠ Shop EjProducts CAT—raininj,

THE SECOND NUMl3EJZ:F_

MULTIPL

ENTER THE FIRST NUMBER:I

ENTER

Page 142: Web Scripting With PHP 1-12

Session 12

64–PTECIf ORLDWIDE

Functions in PHP

............... .. ------ File Edit View Go Bookmarks Tools \M ndcyw Help

httip./flocalhi- S e a r c hBack Forward Reload Stop Print

fjjHome *Bookmarks **_. R e d Hat Network s4 u0 * 1 4 shop (iftProducts EATralrdrK

I THE MULTIPLICATION OF 62 AND 66 IS: 4092

ii

!Wm

Figure 12.7 : Viewing the Result

126 Pang Argument to a. Function 'by, Reference

The second method of passing argument to a function is by passing the reference. When we pass the arguments by reference, the value of the variable is also modified outside the function.

For example, to create a function that calculates the dearness allowance:

Open a new file in the text editor.

Enter the following code to create a form that accepts the basic salary:

<HTML> <BODY>: <B>Using function to .-.,I)A< B> <FORM METHOD= ET ACTION "Dearnessallowance.php"> ENTER YOUR BASIC SALARY: <INPUT TYPE="TEXT". NAME="num1text"> <BR><BR> <INPUT TYPE="SUBMIT" NAME "DEARNESS ALLOWANCE" VALUE=" DEARNESS ALLOWANCE"> <BR> </BODY> </IiTML>

..`,'_-.Enter 62 as the first number.

Enter 66 as the second number.is

10. ,Click the MULTIPLY Ibutton_ N 7-

- - Scripting with PHP V 1 .0 (c) 2004 Aptech Limited Page 145 of 274

Page 143: Web Scripting With PHP 1-12

S e s s i o n 1 2

A P21Y clifWORLDWIDE

Functions in PHP

o calculate e s s , , , A 1 U r.ce-. MN IRA

A

. w . V-NA~

r . 0 - e

M1

............................................................... --,.; - - - - - - - - - - X7

.File Edit View -Go Bookmarks Tools Window Help

\3http:j/l(j'e ~%,,Search Back Forward Reload Stop Print

.,j Home 1 XfBookmarks e Red Hat Network @tsupport QShop CI Products QTM

E N T E R Y O U R B A S I C S A L A R Y :

DEARNESS ALLOWANCE

Done

Figure 12.8 : Dearness Allowance Form

9. ., Enter :2 0 0 0 0 : a s t h e b i i k s a d a r y .

10. Click the DEARNESS ALLOWANCE button. The output appears, as shown in Figure 12.9.

Page 146 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

Page 144: Web Scripting With PHP 1-12

Session 12

('A'Pr'EC'ff7 0 RLDWI WE

Functions in PHP

Figure 12.9 : Viewing the Dearness Allowance

12.7 Setting Defabult Values for an Argument

We can also assign default values to the arguments. We must assign a default value to theargument in the function definition. Now, even if the user tries to pass different arguments, thefunction would process only the default value •

;:--or example, to create a function that has default values for its arguments:

1. Open a new file in the text editor.

2. Enter the following code to calculate the sum of 50 and 100:

<?php function addition($A=50, $B=100) { $C=$A+$B; .echo " The addition of $A and $B is: $C";

} addition();

3. Say.e the file as Additi6n:.php under the /var/www/html.

4. Open the Mozilla Web browser.

5. Type http: / / localhost /Addition. php in the address bar and press the Enter key. The output appears, as shown in Figure 12.10.

.-. z: Scripting with PHP V 1.0 (0 2004 Aptech L imited Page 147 of 2741 Fil Edit Vi G B k k T l Wi d H l

Page 145: Web Scripting With PHP 1-12

Session 12 (A—Pmcm 7 WORLDWIDE

Functions in PHP

Figure 12.10 : Displaying the Sum

12.8 Returning Vai l ues f rom

A function can return values. The return statement returns the value from the function.

For example, to return the cube of a number from the function:

1. Open a new file in the text editor.

2. Enter the following code to create a form that.accepts a number:

<HTML> <BODY> <FORM METHOD=GET ACTION "Cube.php"> ENTER -THE NUMBER:_ <INPUT TYPE="TEXT" NAME="n1text"> <BR> <BR>,: <INPUT. TYPE=,'ISUBMIT" NAME "CUBE" VALUE="CUBE">

<BR> </BODY>. </HTML>

3. Save the file as cube.htmi under the /var/www/htmi directory.

11

Page 148 of 274 V 1.0 @ 2004 Aptech Limited Web Scripting with PH, File

Page 146: Web Scripting With PHP 1-12

Session 12

(A—PYWCH~,W—" LD-W-I 0 E

Functions in PHP

4. Enter the following code to calculate the cube of the number:

< ? p h p

• i4- s z 0 W

Figure 12.11 : Cube Form

8. Enter 10 in the Number text box.

9. Click the CUBE,, qq:..The cube of the numbe appears,as shown in-Figure 12.12. re

11

Scripting with PHP V 1.0 @ 2004 Aptech Limited Page 149 of 274 z 4 f i . . .

Page 147: Web Scripting With PHP 1-12

1-Session 12 WORLDWIDE

Functions in PHP

File Edit View Go Bookmarks Tools Window Help

31 4 http://localh

4k \3 ' ' L G4 -

Print 4* Search

! a H o m e 1 , V$ '.. T';rks eRed Hat Network (,,Isupport Ljshop (4yroducts ffftTralnin

The Cube of 10 is: 1000

0 G 9 D o n e

Figure 12.12 : Displaying the Cube

12.9 -Creatigg Recupive

A function can call itself. When a function calls itself several times, the process is termed as recursion.

For example, to generate the Fibonacci series using the recursive function:

Page 150 of 274 V 1.0 © 2004 Aptech Limited Web Scripting with PHP

1. Open a new file in the text editor.

2. Enter the following code:

<?php $A=O; function fib($A) { if ($A<=1) {

return $A; I else f

return fib($A-1)+fib($A-2);

} while($A!=10)

{ $B=fib($A); echo "$B<BR>" $A++ ;

I

Page 148: Web Scripting With PHP 1-12

Session 12 ~~rEe~ LDWIDE

Functions in PHP a with PHP V 1.0 © 2004 Aptech Limited Page 151 of 274

3. Save the file as - Fibonacci.php under the c' htmi directory.

4. Open the Mozilla Web browser.

5. Type http://localhoet/Fibonacci.html in the address bar and press the EntW key. The output appears, as shown,in; Figure .12.13.

F i le Ed i t V iew Go Bookmarks Too ls Window Help

a 41 4L httn://I(lv Seamh Back Forward Reload Stop ___________________________________

!3 Home I 4Bookmarks eRed Hat Network C4-Support (AShop 8-Products al Tr

0

Figure 12.13 : Displaying the Fibonacci Series

Page 149: Web Scripting With PHP 1-12

Session 12 ~/~YrCHWORLDWI

Functions in PHP

TRY IT YOURSELF

Part II - For the next half an hour:

1. Find and display the minimum number from the following:

55.5, 5555.5, 5.55555555, and 555.55555

2. Find and display the length of the string, WECLCOME.

3. Create a form that accepts the principal amount. Create a user-defined function to calculate the compound interest.

V 1.0 (c) 2004 Aptech Limited Web Scripting with PH:

Page 152 of 274

Page 150: Web Scripting With PHP 1-12

Objectives

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

Define an array

Create and use arrays

Merge arrays

Use single and multidimensional arrays

Use array- related functions

Introduction

Programming languages use variables to store values. An array is a variable that can store a list of values. Arrays can be single-dimensional or multidimensional. All the values are referred by the same array name.

In this session, we will learn how to create and use arrays. We will also learn how to initialize arrays, use single-dimensional and multidimensional arrays. In addition, we will learn to use array-related functions.

Defin;tng an.- Arra variable can store only one value at a time. We can change the value of the variable as many

times as we want in the program. However, we can store only one value in the variable. An array is a variable that can store a set of values of the same data type.

Each value in an array is termed as an element. All the elements are referenced by a common name. Each element of an array can be referred by an array name and an index. An array index is used to access an element. An index can be a number or a string. If the index is a string, the array is an associative array. If the index is a number, the array is an indexed array.

By default, the index value in an array starts at zero. As a result, the index number of the last element in an array is one less than the total number of elements- For example, if there is in an array of five elements, the index number of the last element will be four.

I

I - - Scripting with PHP V 1.0 (c- 2004 Aptech Limited Page 153 of 274

Page 151: Web Scripting With PHP 1-12

Session 13

I (AiMI-EC'N

\17-ort LOWIDE

Working with Arrays

PHP provides us with two ways of initializing an array:

array ( function – Enables to assign value to all the elements of an array array identifier – Enables to assign value to a specific element of an array

A13.2.1 The arrayffunction,

We can create an array and set the initial values of array elements using the array ( ) function.The arrayo function uses key value pairs separated by a comma to create an array. Thenumber of key value pairs in the array() function determines the number of elements in anarray.

The syntax for creating an array using the array() function is:

$array_name = array([key => ] value, [key => value)

Where,

);, array_name - Specifies the array name

key - Specifies the index value of the array element. The key can be a string or an integer. > value - Specifies the value of the element

Using the array() function, we can initialize both indexed and associative arrays.

Indexed Arrays

An indexed array is an array where the index type is integer. By default, PHP creates an indexedarray, if the index type is not specified at the time of creating an array. The index value can startwith any integer, such as 1, 20, or 123.

To create an indexed array named department:

$department = array (1 'Finance', 2 => 'Sales', 3 `HR/ , 4 => 'Purchase')

In the above code snippet, the array Index type is an integer. Note the index value starts from 1. The department array contains three values, Finance, Sales, and HR.

Page 154 of 274

Page 152: Web Scripting With PHP 1-12

(A—PrECM

Se s s i o n 1 3 W O R L D W I D E Working

with Arrays

To view the value of the first element, enter the following:

echo $departmenr-[1]

Note the result of the above code would be Finance.

Associative Arrays

An associative array is an array where the index type is string. In associative arrays, the index value must be specified within double quotes.

To create an associative array named department:

sdenartment = array("a" 'Finance', "b" => 'Sales', 'HR', "d" => 'Purchase')

In the above code snippet, the array index type is a string. Note the index value starts from a. Theindex values are specified within double quotes. The department array contains .three valuesFinance, Sales, and HR.

To view the value of the third element, enter the following:

echo $dcpartment["c"];

Note the result of the above code would be HR.

13.2.2 The Array Identifier

Using the array identifier, we can initialize value of a specific element in an array.

The syntax for creating an array using the array identifier is:

Sarray–rlamo[key] "element value";

Where,

> arry–name - Specifies the name of the array

key - Specifies the index value of the array element. The key type can be a string or an integer.

> element_value - Specifies the value assigned to the element of the array

?,.- -: Scripting with PHP V 1.0 0) 2004 Aptech L imited Page 155 of 274