0% found this document useful (0 votes)
19 views

Server-Side Programming With PHP - I

PHP

Uploaded by

Altaf Mukadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Server-Side Programming With PHP - I

PHP

Uploaded by

Altaf Mukadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT

08 Server-Side Programming
with PHP – I

Names of Sub-Units

Difference between Client-side and Server-side Scripting, Structure of PHP Page, Role of Web Server
Software, PHP Syntax: Variables, Data Types, Decision and Looping with Examples, Comments in PHP,
Echo and Print, PHP Operators, PHP and HTML, Arrays

Overview
The unit discusses difference between client-side and server-side scripting. Next, the unit discusses the
structure of PHP page and role of Web server software. Then, the unit explains the different types of
syntax in PHP. Further, the unit discusses about decision making and looping statements in PHP. The
unit also discusses about comments in PHP. Then, the unit explains echo and print statements. Next,
the unit explains PHP operators and PHP with HTML. Towards the end, the unit explains about arrays
in PHP.

Learning Objectives

In this unit, you will learn to:


 Explain the difference between client-side and server-side scripting
 Describe the structure of PHP page
 Discuss the role of Web server software
 Elucidate the basic concepts of PHP such as variables, data types, decision and looping etc.
 Describe the echo and print statements in PHP
 Explains the PHP operators and PHP with HTML
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

Learning Outcomes

At the end of this unit, you would:


 Examine the difference between client-side and server-side scripting
 Assess the knowledge about the structure of PHP page and the role of Web server software
 Analyse how to create programs in PHP using variables, data types, loops etc.
 Evaluate the significance of the echo and print statements in PHP
 Understand the PHP operators and PHP with HTML

Pre-Unit Preparatory Material

 https://www.php.net/manual/en/language.control-structures.php
 https://www.php.net/manual/en/reserved.variables.php

8.1 INTRODUCTION
Hypertext Preprocessor (PHP) is a server-side scripting language that is used to create dynamic Web
pages. It was created by the Danish programmer, Rasmus Lerdorf, in the year 1995, and was originally
called as Personal Home Page. Lerdorf initially created a set of Common Gateway Interface binaries,
written in C language, to replace some Perl scripts in his homepage. He later combined these binaries
with his Form Interpreter (FI) to create PHP/FI. Although, not officially launched, this PHP/FI was the
first version of the PHP language. PHP/FI had the capability to communicate with database and develop
dynamic Web pages. PHP is free software released under PHP License, which does not adhere to the
GNU General Public License (GPL) norms.

8.2 DIFFERENCE BETWEEN CLIENT-SIDE AND SERVER-SIDE SCRIPTING


There are mainly two types of scripting languages client-side scripting language and server-side
scripting language. Table 1 shows some of the differences between these two types of languages:

Table 1: Differences between client-side scripting and server-side scripting languages

Client-side Scripting Server-side Scripting

It runs on user’s computer. It runs on web server.

It has some dependency on the web browser. It is not dependent on the web browser.

It is faster and more interactive. It depends on the speed of the Internet.

It is not secure in context of data security. It is secure.

It may not require the Internet connection every time. It always requires the Internet connection.

2
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Client-side Scripting Server-side Scripting

HTML, JavaScript, VBScript, etc. are some of the JSP, ASP.NET, PHP, Python, etc. are some of the
examples of client-side scripting language. examples of server-side scripting language.

8.3 STRUCTURE OF A PHP PAGE


PHP pages are plain-text files containing PHP instructions, JavaScript, and HTML language. The
following code shows showing structure of a PHP page:
<html>
<head>
<title> PHP </title>
<head>
<body>
<?php
//this line of code displays a simple text
echo "Introduction to PHP ";
?>
</body>
</html>
In the given code, you can see that the code looks like a HTML page. All the common tags like <html>,
<head>, <title> and <body> are used in a PHP page. The only difference is that the PHP instructions are
written between the <?php … ?>tags. The echo statement is used to display output to the user. The Print
statement can also be used to display output instead of the echo statement.

The following points needs to be kept in mind while working with a PHP page:
 All PHP code must be enclosed within <?php. . . ?> tags
 Every PHP statement must end in a semicolon
 Blank lines within the PHP tags are ignored by the parser
 Single line comments must be preceded by the // characters, while multiline comments must be
enclosed within a /* . . . */ comment block

8.4 ROLE OF WEB SERVER SOFTWARE


As you know that a web server is a software that is used to receives request from a user for a web resource
and sends response to the user with the requested web resource through Hypertext Transfer Protocol
(HTTP). A web server comprises of different types of services, which help network administrators to
efficiently manage Web site. For example, the File Transfer Protocol (FTP) service provided by the web
server is used to upload and download files from the server; the Simple Mail Transfer Protocol (SMTP)
service provided by the web server allows users to exchange emails.
As you know that PHP is a server-side scripting language, it requires a web server to run. A web server
receives your request, recognizes that the file was a PHP script (by means of the .php file extension), and
hands it over to the PHP parser and interpreter for further processing. This PHP interpreter then reads
the instructions between the <?php. . . ?>tags, executes them, and passes the result to the back server,
which in turn sends them back to your browser.

3
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

8.5 PHP SYNTAX


PHP allows you to create dynamic Web pages by embedding PHP scripts in an HTML page using the
<?php and ?>tags. You can save a PHP file with the extensions .php, .php3, .phtml,.ph3, .ph4, .php5, and
.ph5. It is important to note that each PHP statement must end with a semicolon. A simple example of
the PHP statement is the echo statement, which is used to display text on the browser. The following
code snippet shows the use of the echo statement:
<?php
echo "Welcome to PHP!!! ";
?>
In the preceding code snippet, the echo statement is used to display the Welcome to PHP!!!

message on the browser.

In this section, you learn about the following fundamental concepts of PHP:
 Variables
 Constants
 Strings
 Operators

8.5.1 Variables
At times you need to use a text or a number again and again throughout your program. In such cases,
we use variables, which act as containers to store values. In PHP, the name of a variable starts with the
$symbol. The syntax to define a variable is given as follows:
$variable_name = Value;
In the preceding syntax, variable_name is a user-defined variable that can store any type of value, such
as a string or an integer. It is important to note that PHP variables are case sensitive, which means the
variable name, $teststring , is different from the variable name, $TESTSTRING.

The following code snippet shows an example of declaring a variable using PHP script:
$mystring= "Hi from PHP";
Note that in PHP, you do not require to declare a variable in order to use it. In addition, PHP automatically
converts a variable to the correct data type on the basis of its assigned value. Some naming conventions
that must be followed while declaring a variable using PHP are as follows:
 A variable name must begin with a letter or an underscore (_)
 A variable name can contain alphabets (upper case and lower case both), numbers, and underscores
 A variable name should not contain spaces

The following PHP program shows the various operations on a variable:


<?php
$current_value = 10; // assigning value to variable
$value = $current_value; // assigning variable to another variable

4
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

$next_value = $value + 1; // perform calculation


echo "$value comes after $current_value"; // output: '11 comes after 10'
?>
In the given PHP program, the $current_value variable is assigned value, 10. The $current_value variable
is then assigned to the $value variable. The next statement increments the value of the $value variable
by 1 and stores itin the $next_value variable. The value of the $next_value is then printed by using the
echo statement. You can also assign values to variables by using the assign by reference method. In this
method, the new variable points to another variable and changes done in any of the variables affect
both the variables. In this method, the variable name must be preceded by an ampersand(&) sign before
passing its reference to another variable.

The following PHP program shows an example of assigning a value to a variable by assign by reference
method:
<?php
$name = 'Dreamtech Press'; // Assign the value 'Dreamtech Press' to $name
$alt_name = &$name; // Reference $name via $alt_name.
$alt_name = "We are $alt_name"; // Alter $alt_name
echo $alt_name;
echo $name; // $name is altered too.
?>
In the given PHP program, the $name variable is assigned a string value, Dreamtech Press, and the
$alt_name variable is assigned the reference of $name. In the next statement, the $alt_name variable
is now assigned a string We are $alt_name. The value of the $alt_name and $name variables are then
printed using the echo statement. You must note that when the value of $alt_nameis changed, then the
value of $name is also changed, as in this case both the variables print the same value.

8.5.2 Constants
Constants are identifiers that store values, which cannot be changed during the execution of the script.
You can store data, such as configuration settings, whose value does not change during the execution
of the script. Constants are also used to represent integer values with special meanings in a particular
context, such as error codes and flags. It is important to note that constants are case sensitive. By
convention, the constant identifier name is always in uppercase. Constants follow same naming rules
as variables; however, unlike variables the constant names do not start with the $ sign. A valid constant
name starts with a letter or underscore, followed by any number of letters, digits, or underscores. The
syntax to create a constant is as follows:
define ( "CONSTANT_NAME", constant_value );
In the preceding syntax, CONSTANT_NAME refers to the name of the constant and constant value refers
to the value that the constant holds. For example,
define("HELLO", hello)
define("USER_NAME", Rahul)

8.5.3 Strings
A string is a collection of characters. You can perform many operations with strings, such as converting
a lowercase string in upper case string or replacing a string with another one. You can also join two

5
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

strings together with the help of the dot (.) symbol. PHP also provides some methods that are used to
handle strings. Table 2 describes some commonly used built-in string methods:

Table 2: Built-in String Methods

Method Description
trim() Eliminates extra spaces from start and end of a string
substr() Picks substring from a string
strpos() Locates position of substring in a string
ucfirst() Capitalizes first letter of string
substr_replace() Replaces a substring with specified string
strtoupper() Converts a string in uppercase

8.6 DATA TYPES


The following are the data types in PHP:
 Integers: Represents a whole number with no fractional components, such as -21,0,67. The permissible
range of the integer data type varies. The range is decided by the operating system, generally a range
of -2,147,483,648 to +2,147,483,647 is used. Integers can be written in decimal (1, 786, -32, +1063856),
octal (01, 0123, +05, -0123456), or hexadecimal (0x1, 0xff, 0x1a3, +0x6, -0x1a234d) format.
 Floating point numbers: Represents real numbers that include decimal place. PHP includes two
types of floating point numbers. The first is a simple numeric literal with a decimal point. The second
is a floating point number written in scientific notation. Scientific notation is in the form of [number]
E[exponent]. For example, 1.23, 0.003, -2.13, 0.214E2, -3.14E-3.
 Strings: Represents text literals of arbitrary length. In PHP, strings are enclosed within single quotes
or double quotes. Strings inside double quotes are parsed, while strings inside single quotes are
not. It means that if variables or special characters are enclosed in double-quotes with strings,
then the values of variables are printed with the specified string. When variable names and special
characters are enclosed in single quotes, then the output is printed in the same way as you typed
them.
 Booleans: Represents a true or false value. All conditions return a true/false boolean value based on
the condition being tested.
 Array: Represents a variable that stores a collection of related data elements. Each individual
element of an array can be accessed by referring to its index position. The position is either specified
numerically or alphabetically.
 Object: Allows you to store data as well as information to process that data. The data elements
stored within an object are referred to as its properties or attributes of the object. To declare objects,
first you must declare a class of object. Then you need to instantiate the object. Objects also allow
you to create your own data types. You can define the data type in the object class, and then use the
data type in instances of that class.

6
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

 Resource: Represents a special data type, which stores references to functions and resources
external to PHP. The most common example of the resource data type is a database call.
 NULL: Represents a special data type that can have only one value, null. Null is not only a data type,
but also a keyword literal. A variable of the null data type is a variable that has no value assigned to
it. When no value is assigned to a variable, it is automatically assigned a value, null.

The following PHP program shows an example of determining a variable datatype using the gettype()
function:
<?php
$we_are = 'Demo'; // define string variable echo gettype($we_are); //
output: 'string'
$we_are = 99.8; // assign new integer value to variable echo gettype($we_
are); // output: 'double' unset($we_are); // destroy variable
echo gettype($we_are); // output: 'NULL'
?>
In the given PHP program, the gettype() function is used to determine the datatype of a particular
variable. The $we_are variable is assigned the value, Demo. Therefore, PHP sets the datatype of the
$we_are as string. Further, the value of $we_are is changed to 99.8 which makes it a floating point
variable. Next, the variable is destroyed using the unset() function which makes it a NULL type variable.

In addition to gettype(),PHP uses a number of specialized functions to check the datatype of a


variable,which are listed in Table 3:

Table 3: List of specialized functions

Functions Purpose
is_bool() Tests if a variable holds a Boolean value
is_numeric() Tests if a variable holds a anumeric value
is_int() Tests if a variable holds an integer
is_float() Tests if a variable holds a floating-point value
is_string() Tests if a variable holds a string value
is_null() Tests if a variable holds a NULL value
is_array() Tests if a variable is an array
is_object() Tests if a variable is an object

8.7 DECISION MAkING STATEMENTS


Conditional statements are also known as decision making statements. Conditional statements help the
program to decide whether the condition given in the scrip is true and false. The conditions provided in
the statements can be single or multiple and it allows to branch the path of execution in a script based
on whether a single, or multiple conditions, evaluate to true or false. In PHP, there are four types of
conditional statements, which are:
 The if Statement
 The if-else Statement

7
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

 The if-else if-else Statement


 The switch-case Statement

8.7.1 The if Statements


The If Statements always begin with if and followed by a condition provided in parentheses. If the
condition is evaluated and found true, the statement or statements immediately following the condition
are executed. On the other hand, if the condition is found false, no change takes place and you get a
blank browser window when the script is run. The syntax for an if statement is as follows:
if (expression)
statement
When you have more than one statement to be executed within a condition, it is necessary to provide
them in brackets

The following PHP program shows the if condition having more than one statement:
<?php
$x=1;
if ($x == 1)
{
print '$x is equal to 1 <br>';
$x++;
print 'now $x is equal to 2';
}
?>
The output of the given program is as follows:
$x is equal to 1
Now $x is equal to 2
In the given PHP program, if the condition stated in the if block is true, then two messages, $ x is equal
to 1 and $ x is equal to 2, get displayed. First, the PHP parser executes the $ x is equal to 1 statement,
then increments the value of $ x by 1, and then executes the Now $x is equal to 2 statement. However, if
the condition is false, then only a blank Web page is shown as the output. You can write the conditional
statements in different ways.

8.7.2 The if-else Statements


The if-else statements are used to make two types of decisions, such as true and false, based on a
condition. When the condition is true, the if statement is executed and when the condition is false, the
else statement is executed. The syntax for the if-else statement is as follows:
if (condition)
{
statements_1
}
else
{
statements_2
}

8
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

The following PHP program shows an example to understand the script of the if-else statement:
<?php
$a=34;
$b=23;
if ($a > $b)
{
echo "a is greater than b";
}
else
{
echo "a is not greater than b";
}
?>
The output of the given program is as follows:
a is greater than b
In the given PHP program, the parser checks whether or not the condition($a>$b) stated in the if block
is true. In case the condition is true, the block of statement executes displaying the message, a is greater
than b. However, if the condition is false, then the control transfers to the else block. In this case, the
block of code inside the else block is executed, displaying the message, a is not greater than b.

8.7.3 The if-elseif-else Statement


A combination of if-elseif-else statements is evaluated in a sequence. When the condition within the
if statement is false then the elseif condition is checked and if it is found true, elseif statements are
executed. However, else condition is executed when all the elseif conditions are false. The syntax for if-
elseif-else statement is as follows:
if (condition_1) { statement_1
}
elseif (condition_2) { statement_2
}...
elseif (condition_n_1) { statement_n_1
}
else {statement_n
}

8.7.4 The switch Statements


A switch statement allows a program to evaluate a condition and match the condition’s value to the
statements given in case labels shown in the following syntax. If a match is found, the program executes
the associated statement. The working of the switch statements is similar to the if statements. The
syntax for the switch statement is as follows:
switch (condition)
{ case label_1: statements_1 break;
case label_2: statements_2
break;
...

9
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

default: statements_n
break;
}
First the program looks for a statement in the case labels that matches with the value of condition and
execute the associated statements. If no matching label is found, the program looks for the optional
default statement. However, in the absence of default statement, the program executes the statement
given in the end of the switch statements.

The following PHP program shows an example to understand the script of the switch statement:
<?php
$flower = "rose"; switch ($flower)
{ case "rose" :
echo $flower." costs $2.50"; break;
case "daisy" :
echo $flower." costs $1.25"; break;
case "lily" :
echo $flower." costs $1.50"; break;
default :
echo "There is no such flower in our shop"; break;
}
echo "no match is found";
?>
The output of the given program is as follows:
rose cost$2.50
In the given PHP program, the $flower variable is assigned a value, rose, and then the switch condition
(value of $flower) is matched with the case value given in the switch block. If the case value matches
with the switch condition, then the control flow is transferred to the case statement. The statement
within the case block is executed and the message, Great! Ready to make calculations, is displayed as
output.

8.8 LOOPING STATEMENTS


In programming, it is often necessary to repeat the same block of statements a given number of times,
or until certain conditions are fulfilled. This can be accomplished by using looping statements. Loops
execute a block of statements a specified number of times provided it is true. In PHP, the re are four
types of looping statements:
 The while loop  The for loop
 The do-while loop  The foreach loop

8.8.1 The while Loop


The while loops are the simplest type of loops in PHP. It executes the statements repeatedly, as long as
the while condition is evaluated and found TRUE. The value of this condition is checked each time at
the beginning of the loop, so even if this value changes during the execution of the nested statements,

10
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

execution does not stop until the end of the process. Sometimes, if the while condition is evaluated and
found FALSE from the very beginning, the statements are not executed. The syntax for while loop is as
follows:
while (condition)
{
statement;
}
The following PHP program shows an example to understand the script of the while loop.
<?php
$i=1; while($i<=5)
{
echo "The number is ".$i."<br />";
$i++;
}
?>
The output of the given program is as follows:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
In the given PHP program, the while condition evaluates whether $i is less than or equal to 5. The loop
starts with i=1. The value of i gets increased by 1 each time the loop runs. When the value of i becomes
greater than 5, the statement in the braces is skipped and the loop exits without performing any tasks.
However, the value of i is not greater than 5, the statement in the braces is executed and the loop returns
to the while statement. The process repeats until $i is greater than 5.

8.8.2 The do-while Loop


The do-while loops always executes the block of statements at least once and then checks the condition,
and repeats the loop if the condition is true. The syntax for the do-while loop is as follows:
do
{
statement;
}
while (condition);
The following PHP program shows an example to understand the script of the do-while loop.
<?php
$i=1;
do
{
$i++;
echo "The number is".$i."<br />";}
while ($i<=5);
?>

11
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

The output of the given program is as follows:


The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
In the given PHP program, the value 1 is assigned to the $i variable. The value of i is incremented by 1
each time the loop runs. If the value of i is already greater than 5, then the loop exits. If $i is not greater
than 5, the statement in the braces executes and the loop returns to the do-while statement. The process
repeats until $i is greater than 5, and the message is display as an output..

8.8.3 The for Loop


The for loop is used when you know how many times you want to execute a statement or a list of
statements. For this reason, the for loop is also known as definite loop. The syntax of for loops is a bit
more complex as compared to while loop and do while loop. The for loop syntax is as follows:
for (initialization; condition; increment/decrement)
{
statement;
}
The for statement takes three expressions inside its parentheses, separated by semi-colons, which are
as follows:
1. The initializing expression is executed. This expression usually initializes one or more loop counters,
but the syntax allows an expression of any degree of complexity.
2. The condition expression is evaluated. If the value of condition is true, the loop statements execute.
If the value of condition is false, the for loop terminates.
3. The update expression increment/decrement executes.
4. The statements execute, and control returns to step 2.

The following PHP program shows an example to understand the script of the for loop.
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is".$i."<br />";
}
?>
The output of the given program is as follows:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

12
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

In the given PHP program, the value 1 is assigned to the $i variable. The loop iterates as long as the
value of the $i variable is less than or equal to 5. After each iteration, the value of the $i variable is
incremented by 1. The statement inside the loop is executed until the condition is true.

8.8.4 The foreach Loop


The foreach loop is a variation of the for loop and allows you to iterate over elements in an array. There
are two different versions of the foreach loop, which are given in the syntax. The foreach loop syntaxes
are as follows:
foreach(arrayasvalue)
{
statement;
}
foreach(arrayaskey=>value)
{
statement;
}
The following PHP program shows an example to understand the script of the foreach loop.
<?php
$email= array('yogendra gupta','sulabh dixit'); foreach ($email as
$value)
{
echo "Processing ".$value."<br />";
}
?>
The output of the given program is as follows:
Processing yogendra gupta
Processing sulabh dixit

8.8.5 Defining the Nested Looping Statement


The placement of one loop inside the body of another loop is called nesting. When you nest two loops, the
outer loop controls the number of iterations of the inner loop. You can nest all types of loops.

The following PHP program shows an example to understand the script of the nested looping statement.
<?php
for($num2 = 0; $num2 <= 2; $num2++)
{
for($num1 = 0; $num1 <= 1; $num1++)
{ Inner Loop Outer Loop
echo $num2. " And ".$num1."<br/>";
}
}
?>
In the given PHP program, two for loops are used, outer and inner. In the outer for loop, the $num2
variable is initialized as zero and a condition is set to evaluate whether the value of the $num2 variable

13
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

is less than or equal to 2. If the specified condition is true, that is, if the value of the $num2 variable is less
than or equal to 2, the inner for loop is executed. In the inner for loop, the $num1 variable is initialized
as zero and a condition is set to check whether the value of $num1 is less than or equal to one. If the
condition of inner for loop is true, then the value of $num1 is incremented by 1 and the echo statement
of the inner for loop displays the result to the user. When the program is executed for the first time,
the initial values of the $num2 (0) and $num1 (0) variables are displayed to the user. The inner for loop
is executed until the value of the $num1 variable does not exceed beyond 1. Once the value of $num1
exceeds 1, the control of the program is transferred to the outer for loop and checks the condition. The
process of checking the condition of the outer for loop and transferring control to the inner for loop
continues as long as the value of the $num2 variable remains less than or equal to 2. The output of the
given program is as follows:
0 and 0
0 and 1
1 and 0
1 and 1
2 and 0
2 and 1

8.9 BREAk, CONTINUE, AND EXIT STATEMENTS


Sometimes the loops start without any condition, and allow the statements inside the brackets to decide
when to exit the loop. There are three special statements that can be used inside a loop, which are:
 Break
 Continue
 Exit

8.9.1 The Break Statement


The break statement, when enter in a loop skips the remaining statements in the loop body and breaks
the loop. Optionally, you can put a number after the Break keyword indicating how many times you
want to break the loop. The syntax for break statement is as follows:
for (condition)
{
if (condition)
}
break; statement;
statement;
statement;
}
The following PHP program shows an example to understand the script of the break statement.
<?php
for ($i=0; $i<=10; $i++)
{
if ($i==3)
{

14
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

break;
}
echo "The number is ".$i; echo "<br />";
}
echo " This is break statement";
?>
The output of the given program is as follows:
The number is 0
The number is 1
The number is 2
This is break statement
In the given PHP program, the 0 value is assigned to the $i variable. The loop iterates as long as the
value of the $i variable remains less than or equal to 5. After each iteration, the value of the $i variable
is incremented by 1. In this program, the for loop consists of the if condition, which contains a break
statement. The execution of the loop terminates and the message is displayed as the output, if the
condition is true.

8.9.2 The Continue Statement


The continue statement also skips all remaining statements in the loop for the current iteration, but
returns to the top of the loop and allows it to continue running. The syntax for continue statement is as
follows:
for (condition)
{
if (condition)
}
continue;
statement;
statement;
}
The following PHP program shows an example to understand the script of the continue statement.
<?php
for ($i = 0; $i< 5; ++$i)
{
if ($i == 2)
{
continue;
}
echo "The number is: ". $i; echo "<br>";}
?>
The output of the given program is as follows:
The number is: 0
The number is: 1
The number is: 3
The number is: 4

15
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

In the given PHP program, the 0 value is assigned to the $i variable. The loop iterates as long as the
value of the $i variable remains less than or equal to 5. After each iteration, the value of the $i variable
is incremented by 1. In this program, the for loop consists of the if condition, which contains a continue
statement. The current iteration of the loop is terminated, if the condition is true. The control returns to
the top of the loop, restarting the cycle once again.

8.9.3 The Exit Statement


The exit statement is used when you want to stop a program from running. It can block infinite looping
statements in the program. The syntax for exit statement is as follows:
for (condition)
{
if (condition)
}
exit;
statement;
statement;
}
The following PHP program shows an example to understand the script of the exit statement.
<?php
for ($i = 0; $i< 5; ++$i)
{
if ($i == 2)
{
exit;
}
echo "The number is: ". $i; echo "<br>";
}
echo " This is exit statement";
?>
The output of the given program is as follows:
The number is: 0
The number is: 1
In the given PHP program, the 0 value is assigned to the $i variable. The loop iterates as long as the
value of the $i variable remains less than or equal to 5. After each iteration, the value of the $i variable
is incremented by 1. In this program, the for loop consists of the if condition, which contains an exit
statement. The execution of the script terminates and the message is displayed as the output, if the
condition is true.

8.10 COMMENTS IN PHP


Similar to a programming language, PHP also allows you to add comments to your code. Comments
are chunks of text that are ignored at the time of the execution of PHP code by the PHP engine. The
comments might be useful for the programmers to read and understand the flow of the code.

16
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

The PHP script allows you to comment the code in the following ways:
 r Using the /* and */ symbols that can comment the code of multiple lines
 r Using the // symbol at the start of a code line
 r Using the # symbol at the start of a code line

The following code snippet shows the use of comments in a PHP script:
<?php
/* This is comment of Type 1*/
//This is comment of type 2
#This is comment of type 3
echo "Hi from PHP";
?>

8.11 THE ECHO AND PRINT STATEMENTS


The echo statement is used to display a message on a Web browser. The syntax to use the echo statement
is as follows:
<?php
echo "message to be displayed";
?>
Following code snippet show the code to use the echo statement:
<?php
echo "Hi from PHP";
?>
In the preceding code snippet, an echo statement is used to display a simple message, Hi from PHP, on
a Web browser. On the other hands, the print statement also used to display message on the screen. The
main difference between these two statements is that the echo has no return value while print has a
return value of 1 so it can be used in expressions. Following code snippet show the code to use the print
statement:
<?php
print "Hi from PHP";
?>
In the preceding code snippet, a print statement is used to display a simple message, Hi from PHP, on a
Web browser.

8.12 PHP OPERATORS


You can use operators in PHP to perform various operations, such as assign, multiplication, addition,
subtraction, and concatenation, on variables and values. Operators in PHP work with operands, which
specify the variables and values that are to be used in a particular operation. PHP offers different types
of operators, which are as follows:
 Assignment Operators
 Arithmetic Operators

17
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

 String Operators
 Comparison Operators
 Logical Operators
 Increment/Decrement Operators
 Arithmetic Assignment Operators
 Operator Precedence

8.12.1 Assignment Operators


Assignment operator is used to assign values to variables or assign one variable to another as a value.
Such an assignment of value is done with the equal (=) o perator.

For Example:
$my_var = 9;
$another_var = $my_var;
Both the $my_var and $another_var variables contain the value, 9. Assignment operators can also be
used in conjunction with arithmetic operators..

8.12.2 Arithmetic Operators


Arithmetic operators are used to perform basic mathematical operations, such as addition, subtraction,
multiplication, division, and modulus. Table 4 lists the arithmetic operators used in PHP:

Table 4: List of Arithmetic Operators

Example Name Result


-$x Negation Displays opposite of $x
$x+$y Addition Displays addition of $x and $y
$x-$y Subtraction Displays difference of $x and $y
$x*$y Multiplication Displays product of $x and $y
$x/$y Division Displays quotient after dividing $x by $y
$x%$y Modulus Displays remainder after dividing $x by $y

8.12.3 String Operators


The String concatenation operator is used to combine values to create a string. The string concatenation
operator is represented by a period (.) and can be used to build a string from other strings, variables
containing non strings (such as numbers) and even constants.

The following PHP program shows an example of concatenating strings using the string concatenation
operator:
<?php
echo 'We are'. 'Dreamtech India';
?>

18
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

In the given PHP program, the string concatenation operator is used to concatenate two strings. The
second string is appended to the end of the first string, which gives the output, We are Dreamtech India.
You can also use the string concatenation operator to concatenate the values of two variables.

An example of concatenating the values of variables is shown in the following PHP program:
<?php
$myColor='black';
echo 'My favorite color is'.$myColor;
?>
In the given PHP program, the value of the $myColor variable is appended at the end of the string, My
favorite color is, by using the concatenation operator. The echo statement now prints the string, My
favorite color is black. Let’s now learn about comparison operators.

8.12.4 Comparison Operators


The comparison operators are used to compare one value with another and return either a true or false
depending on the status of the match. For example, you can use a comparison operator to check if a
variable value matches a particular number or whether one string is identical to another or not. PHP
provides a wide selection of comparison operators.

The comparison operators are used with two operands, one to the left and one to the right of the operator.
Table 5 lists the comparison operators used in PHP:

Table 5: List of Comparison Operators

Operator Type Description


== Equal to Returns true if first operand is equal to second
!= Not equal to Returns true if first operand is not equal to second
<> Not equal to Returns true if first operand is not equal to second
=== Identical to Returns true if first operand is equal to second in both value and type
!== Not identical to Returns true if first operand is not equal to second in both value and type
< Less than Returns true if first operand is less than the second operand
> Greater than Returns true if first operand is greater than second
<= Less than or equal to Returns true if first operand is less than or equal to second
>= Greater than or equal Returns true if the first operand is greater than or equal to the second
to operand

8.12.5 Logical Operators


Logical Operators are also known as boolean operators because they evaluate parts of an expression
and return either true or false.

19
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

Table 6 lists the logical operators used in PHP:

Table 6: List of Logical Operators

Operator Type Description


and AND Performs a logical AND operation
or OR Performs a logical OR operation
xor XOR Performs a logical XOR(exclusive OR) operation
&& AND Performs a logical AND operation
|| OR Performs a logical OR operation

8.12.6 The Increment/Decrement Operators


Other useful operators used in PHP are: Increment/Decrement Operators. Table 7 shows the List of
Increment/decrement operators:

Table 7: List of Increment/DecrementOperators

Example Name Effect


$x++ Post Increment Returns the value of $a, and then increments its value by one
++$x Pre Increment Increments the value of $a by one, then returns the value of $a
$x-- Post Decrement Returns the value of $a, and then decrements its value by one
--$x Pre Decrement Decrements the value of $a by one, then returns the value of $a

You can use increment/decrement operators with variables. An example of using increment/decrement
operators with variables is shown in the following PHP program:
<?php
$x = 19; // define variable
$y=$x++; // post increment echo $y; // output: 19
$y=++$x; // pre increment echo $y;// output:21
$y=$x--; // post decrement echo $y; // output: 21
$y=--$x; // pre decrement echo $y; //output:19
?>
In the given PHP program, the $x variable is assigned the value, 19, and then $x is assigned to the $y
variable. Therefore, now $y has value 19 and then the value of $x is incremented by 1. Now, the value
of $x is 20. The echo statement prints the value of $y as 19. This is known as post increment. In pre
increment, the value of $x is first incremented by 1 and then its incremented value, 21, is assigned to $y.
Therefore, now both $x and $y contains value, 21. The echo statement now prints the value of $y as 21.
Similarly, the post and pre decrement operations are performed in the next statements.

8.12.7 Arithmetic Assignment Operators


The arithmetic assignment operators are a combination of arithmetic and assignment operators. They
first perform the basic arithmetic operations on variables and then assign the resultant value to a
variable itself.

20
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Table 8 shows the list of some arithmetic assignment operators:

Table 8: List of Arithmetic Assignment Operators

Operator Description
+= Adds the value and assigns it to a variable
-= Subtracts the value and assigns it to a variable
*= Multiplies the value and assigns it to a variable
/= Divides the value and assigns it to a variable
%= Divides and assigns the modulus to a variable
.= Concatenates and assigns the value(for strings only) to a variable

You can use arithmetic assignment operators to perform various operations as shown in the following
PHP program:
<?php
$x=9;
$x+=2; //similar to $x=$x+2 echo $x; //displays 11
$x-=3; //similar to $x=$x-2 echo $x;//displays 8
$x*=2; // similar to $x=$x*2 echo $x;// displays 16
$x/=2; //similar to $x=$x/2 echo $x;// displays 8
$x%=3;// similar to $x=$x%3 echo $x;// displays 2
$x= 'We are';
$x.= 'Indians';
echo $x; // displays 'We are Indians'
?>
In the given PHP program, the $x variable is assigned a value, 9, and in the next statement, its value is
incremented by 2 and assigned to itself. Therefore, now its value is 11, which is printed using the echo
statement. Similarly, other assignment operators are used in next statements.

5.12.8 Operator Precedence


Operator precedence refers to the strength with which the two operators are bound together. For
example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication (*) operator
has a higher precedence than the addition (+) operator.

The following program shows an example of operator precedence:


<?php
echo 5*2+1;// displays 11
echo 5+2*1;// displays 7
echo 5*(2+1);// displays 15
?>
In the given PHP program, the first echo statement prints 11 while the next echo statement prints 7. This
is because the precedence of the * operator is higher than the + operator; therefore, in the first statement
the expression is evaluated as (5*2)+1 and in the second case it is evaluated as 5+(2*1). Parenthesis is
used to force precedence which is seen in the third echo statement where (2+1) is evaluated first and its

21
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

result is then multiplied with 5 and the output is 15. If the operators have same precedence then left to
right associativity decides the order of precedence.

Table 9 lists the precedence of operators with the highest-precedence operators listed at the top of the
table and operators on the same line have equal precedence:

Table 9: Precedence of Operators

Associativity Operators Additional Information


Right ! Logical
Left */% Arithmetic
Left +-. Arithmetic and string
Left & Bitwise and references
Left | Bitwise
Left && Logical
Left || Logical
Right =+=-=*=/=.=%=&=|=^=<<=>>= Assignment
Left and Logical
Left xor Logical
Left or Logical
Left , Many uses

8.13 PHP AND HTML


The PHP code needs to be embedded in either the HTML or Extensible Hypertext Markup Language
(XHTML) language, as only these are supported by the Web browser. Apart from PHP, the JavaScript
language can also be embedded in the HTML or XHTML languages to help perform certain tasks at the
client side; thereby, reducing the burden on the Web server. A simple HTML document is used to create
static Web pages; however, dynamic pages can also be created by embedding scripts, such as PHP and
JavaScript in the HTML document.

8.14 ARRAYS
You have already learnt that a variable is a storage area holding numbers and text. The problem is that
a variable can hold only one value at a time while an array is a special variable, which can hold more
than one value at a time. An array can hold all variable values under a single name. You can access the
values of an array by referring to the array name.

8.14.1 Creating an Array


Creating an array in PHP is a simple task. An array() construct is used in PHP to create an array. Let’s
start with creating an empty array. That is, an array with no index or values.

22
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

The following PHP program shows how to create an empty array using the array() construct:
<?php
//create an empty array
$array=array();
?>
In the given PHP program, we have created a variable named $array, which is an empty array using
array()construct. PHP provides a is_array() function to check if a variable is an array or not. The is_
array()function takes a variable as its only argument and returns a Boolean TRUE if the variable is an
array else itreturns FALSE.

The following PHP program checking the $array variable:


<?php // create an empty array
$array = array();
if(is_array($array)) //check if $array is an array
{ // if it is an array
echo "Variable is an array"; }
else { // if it is not an array
echo "Variable is not an array"; }
?>
The output of the given program is as follows:
Variable is an Array
In the given PHP program, we first create an empty variable, $array and then we check whether this
variable is an array or not using the is_array() function. The output variable is an array shows that the
variable, $array is an array. As mentioned above an array is map of key (index) and value pairs. Each
key is assigned a value. The value can be in the form of variables, arrays, or objects.

The following PHP program shows how to create an array with elements:
<?php
// create an array with some element
$cars = array('Lio', 'Spark', 'Scorpio', 'Safari');
?>
In the given PHP program, we have not specified any keys (indexes). If no key is specified, PHP
automatically assigns a numeric value to the key, thus creating a numeric array. The count of the index
begins at zero (0).You have learned to create an array with elements, lets learn to print the elements of
an array.

The following PHP program shows how to print the elements of an array using the print_r() function:
<?php
// create an array with some element
$cars = array('Lio', 'Spark', 'Scorpio', 'Safari');
//print the array contents
print_r( $cars );
?>
The output of the given program is as follows:
Array ( [0] =>Lio [1] => Spark [2] => Scorpio [3] => Safari )

23
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

In the given PHP program, first we create array variable $cars with elements Lio, Spark, Scorpio, Safari
and then print the elements using the print_r() function.

Note:

The print_r() function outputs human-readable information about a variable and is an excellent tool
for quicklydebugging or viewing array contents

8.14.2 Accessing Array Elements


PHP allows direct access to array values by specifying the array name and the index. The following PHP
program shows how to access a specific array element using the index number:
<?php
// create an array with some element
$cars = array('Lio', 'Spark', 'Scorpio', 'Safari');
echo "The second element of the array is: ".$cars[1];
?>
The output of the given program is as follows:
The second element of the array is : Spark
In the given program, we first create an array variable $cars with elements Lio, Spark, Scorpio, Safari
and then access its second element. The array index of 1 (one) has been used within the array index
operators [ ], and the output prints the value of the array element with the index 1, Spark.

8.14.3 Types of Arrays


Following are three types of arrays in PHP:
 Numeric array: Numeric arrays use integer values as their index number to identify each item of
the array.
 Associative array: In an associative array an index is associated with a value. For example, if
you wanted to store the salaries of employees you can use the employees names as the keys in an
associative array and the output value would be their respective salary.
 Multidimensional array: A multidimensional array is an array that can contain sub arrays and
the sub arrays can further contain subarrays within them. You can understand the concept of
multidimensional arrays using the following example. David has two sons Richie and Mason. Richie
has two daughters Sue and Natasha while Mason has three daughters Nichole, Salma and Amber.

8.14.4 Traversing Arrays using Loops and Array Iterators


Array traversal is useful to work on each element of an array, such as, sending a mail to each element
in an array of addresses and updating each file in an array of filenames. There are several ways to
traverse an array in PHP, and the one you choose depends on data and the task you are performing.

PHP 4 has introduced a foreach construct. It provides an easy way to iterate over arrays. foreach works
only on arrays, and issues an error when you try to use it on a variable with a different data type or an

24
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

uninitialized variable. There are two syntaxes for define the foreach loop. Following syntax is used to
define the foreach loop:
First: foreach (array_expression as $value) {
//statement
}
Second: foreach (array_expression as $key => $value) {
//statement
}
In the preceding syntax, first forms a loop over the array given by array_expression. On each loop, the
value of the current element is assigned to $value and the internal array pointer is increased by one.
The second form does the same thing, except that the current element’s index is assigned to the variable
$key on each loop.

The following PHP program shows the use of foreach loop to traverse an array:
<?php
$students = array();
//assigning values
$students[0] = "david";
$students[1] = "kevin";
$students[2] = "julie";
$students[3] = "nayyar";
// now we will use the foreach loop to display all the students names i.e
the array alues
in one go foreach ( $students as $std_name )
{
echo $std_name . "\n";}
?>
The output of the given program is as follows:
davidkevinjulienayyar
In the above code the $std_name works as a temporary variable to get each value of array. When the
loop executes, the next available value of the array overwrites the existing value of the $std_nameand
then $std_name points to the current fetched value. It works just as walking through your array values
one by one.

Every PHP array keeps track of the current element you are working on; the pointer to the current
element is known as the iterator. PHP has a ready-made extensible tool to loop over the array elements
called ArrayIterator (new in PHP 5.0) to set, move, and reset the iterator. The ArrayIterator functions
are:
 current(): Returns the element currently pointed by the iterator
 reset(): Moves the iterator to the first element in the array and returns its value
 next(): Moves the iterator to the next element in the array and returns its value
 prev(): Moves the iterator to the previous element in the array and returns its value
 end(): Moves the iterator to the last element in the array and returns its value

25
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

 each(): Returns the index and value of the current element as an array and moves the iterator to the
next element in the array
 key(): Returns the index of the current element

8.15 LAB EXERCISE


Write a PHP program to display a digital clock which displays the current time of the server.

Ans. The following PHP program displays a digital clock which displays the current time of the server:
<html>
<head>
<meta http-equiv="refresh" content="1"/>
<style>
p {
color:red;
font-size:50px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
body{background-color:yellow;}
</style>
<p> <?php echo date(" h: i : s A");?> </p>
</head>
</html>

Conclusion 8.16 CONCLUSION

 Hypertext Preprocessor (PHP) is a server-side scripting language that is used to create dynamic
Web pages.
 PHP pages are plain-text files containing PHP instructions, JavaScript, and HTML language.
 Web server is a software that is used to receives request from a user for a web resource and sends
response to the user with the requested web resource through Hypertext Transfer Protocol (HTTP).
 PHP allows you to create dynamic Web pages by embedding PHP scripts in an HTML page using the
<?php and ?>tags.
 Constants are identifiers that store values, which cannot be changed during the execution of the
script.
 A string is a collection of characters.
 Conditional statements help the program to decide whether the condition given in the scrip is true
and false.
 Loops execute a block of statements a specified number of times provided it is true.
 The placement of one loop inside the body of another loop is called nesting. When you nest two loops,
the outer loop controls the number of iterations of the inner loop.

26
UNIT 08: Server-Side Programming with PHP – I JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

 The break statement, when enter in a loop skips the remaining statements in the loop body and
breaks the loop.
 The continue statement also skips all remaining statements in the loop for the current iteration, but
returns to the top of the loop and allows it to continue running.
 The exit statement is used when you want to stop a program from running.
 Comments are chunks of text that are ignored at the time of the execution of PHP code by the PHP
engine.
 The echo statement is used to display a message on a Web browser.
 The print statement also used to display message on the screen.
 Operators in PHP work with operands, which specify the variables and values that are to be used in
a particular operation.
 Operator precedence refers to the strength with which the two operators are bound together
 The PHP code needs to be embedded in either the HTML or Extensible Hypertext Markup Language
(XHTML) language, as only these are supported by the Web browser.

8.17 GLOSSARY

 Constants: These are identifiers that store values, which cannot be changed during the execution
of the script.
 Conditional statements: These help the program to decide whether the condition given in the scrip
is true and false.
 Comments: These are chunks of text that are ignored at the time of the execution of PHP code by
the PHP engine.
 Hypertext Preprocessor (PHP): A server-side scripting language that is used to create dynamic Web
pages
 Web server: A software that is used to receives request from a user for a web resource and sends
response to the user with the requested web resource through HTTP

8.18 SELF-ASSESSMENT QUESTIONS

A. Essay Type Questions


1. What is a variable? List the rules and conventions used to declare a variable in PHP.
2. Explain String operator with example.
3. Describe the difference between while loop and do-while loop.
4. Explain different types of arrays in PHP.
5. Define the concept of commenting text in PHP.

27
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Advanced Web Technologies

8.19 ANSWERS AND HINTS FOR SELF-ASSESSMENT QUESTIONS

A. Hints for Essay Type Questions


1. At times you need to use a text or a number again and again throughout your program. In such
cases, we use variables, which act as containers to store values. In PHP, the name of a variable starts
with the $symbol. Refer to Section PHP Syntax
2. The String concatenation operator is used to combine values to create a string. The string
concatenation operator is represented by a period (.) and can be used to build a string from other
strings, variables containing non strings (such as numbers) and even constants. Refer to Section
PHP Operators
3. The while loops are the simplest type of loops in PHP. It executes the statements repeatedly, as long
as the while condition is evaluated and found TRUE. The value of this condition is checked each
time at the beginning of the loop, so even if this value changes during the execution of the nested
statements, execution does not stop until the end of the process. Refer to Section Looping Statements
4. Following are three types of arrays in PHP:
 Numeric array: Numeric arrays use integer values as their index number to identify each item
of the array.
Refer to Section Arrays
5. Similar to a programming language, PHP also allows you to add comments to your code. Comments
are chunks of text that are ignored at the time of the execution of PHP code by the PHP engine. The
comments might be useful for the programmers to read and understand the flow of the code. Refer
to Section Comments in PHP

@ 8.20 POST-UNIT READING MATERIAL

 https://www.codewall.co.uk/5-ways-to-loop-through-array-php/
 https://www.php.net/manual/en/control-structures.elseif.php

8.21 TOPICS FOR DISCUSSION FORUMS

 Search and enlist the differences among various versions of PHP and discuss with your colleagues.
Also, discuss the use of different type of operators in PHP.

28

You might also like