PHP
INDEX
Chapter 1 Introduction to PHP 7
1.1 Installation of PHP 7
1.2 Basics of PHP 10
1.3 Combining HTML and PHP 14
Chapter 2 Fundamentals of PHP 17
2.1 Variables 17
2.2 Data types 18
2.3 Operators 25
2.4 Control structure 30
Chapter 3 Arrays in PHP 33
3.1 Creating arrays 35
3.2 Multi dimensional arrays 37
3.3 Navigating arrays 39
3.4 Manipulating keys 41
3.5 Manipulating arrays 41
3.6 Serialising arrays 48
Chapter 4 Functions in PHP 51
4.1 User defined function 52
4.2 Function scope 54
4.3 Function arguments and return values 54
4.4 Internal function 57
4.5 Static variables 64
Chapter 5 Strings in PHP 66
5.1 Introduction to string 66
5.2 String functions 70
Chapter 6 Object Orientation in PHP 79
6.1 Getting started 79
6.2 Concept of class and object 79
6.3 Classes as namespaces 81
6.4 Objects as references 82
6.5 Implementing inheritance 85
6.6 Method overriding 86
6.7 Magic functions 87
Chapter 7 Working with forms 91
7.1 Global and environmental variable 91
7.2 Script to accept user input 92
7.3 Accessing input from various elements of form 94
7.4 Accessing inputs in an associative array 96
7.5 Get and Post method 98
7.6 File upload 99
Chapter 8 File manipulation in PHP 104
8.1 Testing files 104
8.2 Opening files 108
8.3 Closing files 109
8.4 Reading from a file 110
8.5 Writing to a file 111
8.6 Locking files 111
8.7 Miscellaneous shortcuts 113
Chapter 9 Saving state in PHP 114
9.1 Setting a cookie 114
9.2 Deleting a cookie 115
9.3 Creating session cookie 115
9.4 Working with query string 116
9.5 Session function 117
9.6 Session variables 118
Chapter 10 Advanced concepts in PHP 121
10.1 Date 121
10.2 Include 123
10.3 Email 125
10.4 Secure email 127
10.5 Error 129
10.6 PHP exception 135
10.7 PHP filter 136
Chapter 11 PHP and databases 141
11.1 Database concept 144
11.2 Database connection 145
11.3 Creating tables 146
11.4 Getting information on database 147
11.5 Inserting data to a table 148
11.6 Retrieving data from a table 151
11.7 Changing data of a table 152
11.8 Deleting data from a table 154
Chapter 12 PHP Project 155
PHP, an acronym for Hypertext Preprocessor, is an HTML
embedded scripting language. As a general purpose language,
it is used for web development and HTML. Apart
from being one of the potent, server-side scripting languages,
PHP is also used for creating interactive and dynamic web sites.
The basic syntax of PHP is similar to Perl and C. Due to these similarities,
PHP is often used with the Apache web server on various
operating systems.
In addition to supporting the Internet Server Application
Programming Interface (ISAPI), PHP is also used with IIS on
Windows. Originally designed for creating dynamic web pages, it
has developed as a popular medium for innovative web applications
and has helped in developing some command line interface
mediums. Rasmus Lerdorf is credited with creating PHP in 1995.
Usually, PHP runs on a web server and is available on different operating
systems and platforms. Its ability to run on most web servers
and operating systems for free has added to its demand and esteem.
PHP has the following benefits:
● Creates advanced user experience based on resources already
collected
● Quick solution for large and advanced web sites
● Convenient solutions for e-commerce
● Diverse scopes for creating online tools
According to recent statistical data, PHP is installed on more
than 20 million web sites and around 1 million web servers. The
source code for PHP is distributed under a license, thus making it
easily accessible to users.
1.1. Installation of PHP
There are two ways for installation with Windows. This can be
done either manually or by an installer. You require PHP, a web
browser and a web server.
Introduction to PHP
Normally, there are three common ways of using PHP:
● Desktop (GUI) applications
●Web sites and web applications (server-side scripting), and
● Command line scripting
Once you write the PHP script, the rest of the work is simple.
Assuming that you already have a web browser, and depending on
your operating system setup, you either have a web server for webspace,
or you can rent this from a hosting company. After following
these simple steps, you can simply upload your PHP code on
your rented server and see the results in your browser. PHP can be
compiled from the original source code if Microsoft Visual Studio
is already installed on the local drive.
PHP installation can be categorised into two parts:
Windows installer: Here you use the MSI technology of the Wix
Toolkit. In this method, PHP is installed and configured with PECL
and other built-in extensions. The Windows Installer also configures
many other popular web servers like Apache, Xitami and IIS.
Normal install: While running the MSI installer, follow the
instructions in the installation wizard.
While in some servers PHP has a direct module interface (such
as Microsoft Internet Information Server, iPlanet servers, Apache
and Netscape) many other servers support ISAPI. However, PHP
does not have a module support for web servers. You can host PHP
application with the CGI or Fast CGI processor.
It is often used for command-line scripting with the command
line executable. PHP is an advanced scripting language and can be
used to write desktop GUI applications, making use of the PHPGTK
extension. Writing desktop GUI applications is different from
creating web pages. In a GUI application, PHP manages windows
and objects, but no HTML is produced.
Silent install: It method is helpful for system administrators. The
following command is useful during the installation of PHP in
silent mode:
msiexec.exe /i php-VERSION-win32-install.msi /q
Another useful formula to install PHP is:
I
8
PHP
FAST TRACK
INTRODUCTION TO PHP
msiexec.exe /i php-VERSION-win32-install.msi /q
INSTALLDIR=e: \php
The same command can also be used to target the ‘Apache
Configuration Directory’ (APACHEDIR), ‘the Sambar Server directory’
(SAMBARDIR), or the ‘Xitami Server directory’ (XITAMIDIR).
Some other installation features can also be presented to
install the mysqli extension and the CGI executable. See the following
command:
msiexec.exe /i php-VERSION-win32-install.msi /q
ADDLOCAL=cgi,ext_php_mysqli
Some other features for installation with PHP have been developed
in recent times. These are mentioned below:
MainExecutable - php.exe executable
ScriptExecutable - php-win.exe executable
ext_php_* - various extensions (e.g.: ext_php_mysql for MySQL )
apache13 - Apache 1.3 module
apache20 - Apache 2.0 module
apache22 - Apache 2, 2 module
apacheCGI - Apache CGI executable
iis4ISAPI - IIS ISAPI module
iis4CGI - IIS CGI executable
NSAPI - Sun/iPlanet/Netscape server module
Xitami - Xitami CGI executable
Sambar - Sambar Server ISAPI module
CGI - php-cgi.exe executable
PEAR - PEAR installer
Manual - PHP Manual in CHM Format
While upgrading, you need to run the installer either in a graphic
pattern or perform the entire task manually. The upgraded install
method offers the installer a new installation option to uninstall
the old installation in lieu of the new one.
Manual installation steps: With the help of this guide, you can
manually install and configure PHP with a web server on
Microsoft Windows. To begin the manual installation, download
the ZIP binary distribution. Before entering any server specific
instructions, follow these steps:
9
PHP
To begin with, place the distribution file in a directory. Follow
specific installation methods for installing different PHP versions.
To install PHP 4, extract the files to C:\ and then the ZIP file will
expand into a folder named php-4.3.7-Win32. Similarly, if you are
installing PHP 5, extract the file to C:\php as the zip file does not
expand in the same way as PHP4.
Installing PHP on your operating system helps in many ways. It
can perform any task a CGI program can do. Like a CGI, PHP generates
dynamic page content, collect form data, and even sends
and accepts cookies. Moreover, as an embedded scripting language,
PHP has certain other utilities like:
● Used for server-side scripting
●Writing client-side GUI applications, and
● Used for Command line scripting
Once installed on your Windows system, you can download
some extensions for additional functionality.
1.2 Basics of PHP
Apart from a simple text editor, no other additional software is
required to create PHP code.
First of all in order to print the information about PHP on your
server type the following code into the text editor installed on
your computer.
<?
phpinfo();
?>
This single line of PHP code phpinfo, commands the server
to print a standard information table. This provides information
about the server setup. In the above example, the line ends
with a semicolon and should not be missed, or else you will get
an error.
Save this script as phpinfo.php, and upload it to the server.
Access the URL of the script with your browser. If you can access
the script, you will see detailed information about PHP on your
server.
I
10
PHP
INTRODUCTION TO PHP
If the script fails to work and displays a blank page, then it
indicates either the code is wrong, or the server does not support
this function.
The basic features of PHP can be divided into three major sections:
● Escaping from HTML
● Instruction separation, and
● Comments
Escaping from HTML: Here, a file is analysed and simply parsed
until a special tag is reached. The entire text is interpreted as
PHP code.
Instruction separation: The instructions in PHP code are separated
exactly the same way as in Perl or C. Each statement is terminated
with a semicolon. In PHP, the closing tag suggests the end
of a statement. The syntax is as follows:
<?php
echo “This is used for testing”;
?>
Comments: In PHP, C and C++ style comments are supported along
with Unix shell like comments. The comment comes at the end of
a line or in a PHP block of code.
Any PHP scripting block begins with <?php and ends with ?>.
PHP source code is flexible and can be placed anywhere in a document.
Such source code can never be viewed by selecting the View
Source option in the browser. The only thing that is apparent
while running PHP is the output in HTML format that is created as
the PHP scripts are executed on the server before actually sending
the outcome to the browser.
You can also begin a scripting block with (<?) and end with (?>).
This is just a shortened version. It is always advisable to use the
standard form of (<?php) in place of the shortened form (<?) as the
former is clearer and generally supported.
As in an HTML file, PHP files also have HTML tags in addition
to some PHP script code. Some important examples are given as
11
PHP
below using the text string “Hello World” and sending it to the
browser.
<html>
<body><?php
echo “Welcome”;
?></body>
</html>
Here, each line of PHP code ends with a semicolon. This semicolon
actually acts as a separator between two sets of instructions.
Echo and Print are the two basic statements available to output
text with PHP.
PHP comments: While a single line comment in PHP is made
by using//, a large block comment is indicated by /* and */. The following
example will make this clear:
<html>
<body><?php//Here is a comment/*
It is
inserted in the
block
*/?></body>
</html>
Since, PHP scripts are basically embedded in an HTML document,
you have the freedom to shift between HTML and PHP.
PHP has several important benefits such as:
● It is not restricted to HTML output
● It provides cross-platform functionality
● PHP converses with several network protocols
● It is compatible with a wide variety of databases
● Strong text processing facilities are available
● It supports most current web servers
PHP can be used effectively on different operating systems
such as Linux, Microsoft Windows, many Unix variants (like
Solaris, HP-UX and OpenBSD), Mac OS X, RISC OS, and many others.
As discussed earlier, in the present scenario, PHP supports
most web servers. It works as a CGI processor in servers support-
I
12
PHP
INTRODUCTION TO PHP
ing the CGI standard. Each PHP script remains enclosed between
two PHP tags commanding the server to recognise the information
as PHP.
As PHP is a server-side language, its scripts only run on the
operating web server. They never run in the user’s browser. With
PHP installed in your computer, you can use both procedural programming
and object oriented programming (OOP). In some
recent PHP versions, not every OOP feature is mentioned. Some
code libraries and large applications have been written by using
just the OOP codes.
Let’s see how we can declare some PHP code:
We can declare PHP code in three different forms:
“ <?
PHP Here we insert PHP codes
?>
“ <?php
PHP Here we insert PHP codes
php?>
“ <script language=”php”>
PHP Here we insert PHP codes
</script>
One of the essential features of PHP is that it supports several
databases and so you can write database-enabled web pages. PHP
supports the following databases:
Adabas D Ingres Oracle (OCI7 and OCI8)
dBase InterBase Ovrimos
Empress FrontBase PostgreSQL
FilePro (read-only) mySQL Solid
Hyperwave Direct MS-SQL Sybase
IBM DB2 MySQL Velocis
Informix ODBC Unix dbm
PHP also supports certain other services such as SNMP, LDAP,
POP3, IMAP, HTTP, COM (on Windows), NNTP and many others. The
language has certain useful text processing features from the
13
PHP
INTRODUCTION TO PHP I
POSIX Extended or Perl regular expressions to analysing XML documents.
Some of the important functions performed here include
CyberMUT, Cybercash payment, VeriSign Payflow Pro and CCVS
functions commendable to use for online financial programs.
1.3 Combining HTML and PHP
PHP and HTML are closely related to each other and often function
together. PHP generates HTML and this HTML passes information
to PHP. The two together are seen in the following PHP script
which includes HTML:
1: <!DOCTYPE html PUBLIC
2: “-//W3C//DTD XHTML 1.0 Strict//EN”
3: “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
strict.dtd”>
4: <html>
5: <head>
6: <title>Listing 3.2 A PHP Script Including
HTML</title>
7: </head>
8: <body>
9: <div><b>
10: <?php
11: print “hello world”;
12: ?>
13: </b></div>
14: </body>
15: </html>
Let’s discuss how to make a form in HTML and fill the form
with data using PHP. There are several methods in PHP through
which you can make a form and prepare data for that form. Begin
your task by making an HTML form to retrieve a user date. PHP and
HTML, both are often combined to make bullets, check boxes,
input fields and text fields. Both can be used for making a form
and collecting personal details of users.
Input Fields:
The input fields in HTML are easily understandable. The following
code would present a simple HTML form document.
I
14
PHP
INTRODUCTION TO PHP
Code:
<html>
<head>
<title>individual information</title>
</head>
<body>
<form method=”post” action=”<?php echo $PHP_TUTORIAL;?>”>
First Name:<input type=”text” size=”10”
maxlength=”10” name=”Fnaming”>:<br />
Last Name:<input type=”text” size=”10”
maxlength=”46” name=”Lnaming”>:<br />
Radios and checkboxes:
PHP also plays a significant role while making radio buttons and
checkboxes in HTML. The radio buttons have associated with them
value attributes and the text equated to this value is displayed by
the browser when the variable is set in PHP.
The check boxes in the HTML format are made by using arrays.
With PHP, the check boxes are placed in an array specified by
brackets at the end.
Code:
...
Sex::<br />
Male:<input type=”radio” value=”Male”
name=”Sex”>:<br />
Female:<input type=”radio” value=”Female”
name=”Sex”>:<br />
Please choose type of dwelling::<br />
Steak:<input type=”checkbox” value=”Steak”
name=”food[]”>:<br />
Sandwich:<input type=”checkbox” value=”Sandwich ”
name=”food[]”>:<br />
Fowl:<input type=”checkbox” value=”Fowl”
name=”food[]”>:<br />
Text areas:
In PHP, the text areas are input fields. These are handled according
to the wrap attribute setting. The following code will illustrate this:
15
PHP
...
<textarea rows=”4” cols=”10” name=”quotation”
wrap=”physic”>Insert your preferred
quotation!</textarea>:<br />
Dropdown lists and selection lists:
Dropdown lists and selection lists are similar to radio buttons and
checkbox selections. While naming a selection form, the name
attributes should always be at the beginning. After this put the
appropriate values in the options that are grouped under the
select tag.
Code:
Select a Level of Learning:<br />
<select name=”Learning”>
<option value=”Graduation”>Graduation</option>
<option value=”PostGraduation”>PostGraduation
</option>
<option value=”Institute”>Institute</option>
</select>:<br />
Select your favourite time of Daytime:<br />
<select name=”TofD” size=”3”>
<option value=” Day “>Dawn</option>
<option value=”Daytime”>Daytime</option>
<option value=”Dark”>Dark</option></select>:<br />
Always check the code and look for bugs and errors
while going through each of the names. The following
code will make the indication clear.
“ http://www.indusnetacademy.com/store/”>
<html>
<head>
<title>A PHP Script Including HTML</title>
</head>
<body>
<div><b>
<?php
print “Welcome”;
?>
</b></div>
</body>
</html>
I
16
PHP
Fundamentals of
PHP
(as in $first_name) when two or more words are used to name
them, or by converting the first letter of each word to uppercase
(as in $lastName). This is done simply to make the name more
readable.
Now let us look at the various types of variables:
● Integer: These are whole number(s) (-9, 9, 99, 999, etc).
● Double/Float: These are floating point numbers or real numbers
(0.99, 99.0, etc).
● String: These are strings of characters (“Learn”, “Java and
JavaScript”). This type of variable holds both words and sentences.
Boolean: This holds only two types of data: True and False.
Array: This type of variable holds a list of items.
($student = array(“class”, “section”, “roll”);
Object: This is an instance of a class.
The variable can be accessed from within the ‘Variable Scope’
where it was defined. A variable cannot be accessed if it was
defined in a completely different scope. There are three types of
Variable Scope: Superglobal, Global and Function.
Superglobal: The Superglobal variable is a type of pre-defined
array in PHP. These variables can be accessed from every section of
the code.
Global: Global variables can be viewed throughout the script if
these are declared in it.
Function: Local variables are declared in a function scope.
These variables are exclusively ‘local’ to the function in which
they are declared. These variables cannot be accessed from outside
the Function where it was defined.
In PHP, there are some in-built functions that can check the
authenticity of a variable. The function ‘isset()’ is used to check the
existence of a variable. It returns Boolean result (True or False). To
remove a variable from the memory, the ‘unset()’ function is used.
The ‘empty()’ function is used to check whether a variable has
been defined and holds a non-empty value.
2.2 Data Types:
‘Data Types’ can be divided into two groups: ‘Core Data Type’ and
‘Special Data Type’.
II
18
PHP
FUNDAMENTALS OF PHP
The ‘Core data type’ group includes Integer, Float/Double,
String and Boolean. The ‘Special data types includes Null, Array,
Object and Resources.
Integers: As discussed earlier, Integers are whole numbers. It
does not include precision. Negative values are also regarded as
Integers.
Example: -32, 32, 986, 1245, etc.
Floating-Point Number or Double: Fractional numbers are
grouped as Floating point numbers or Double data type. Simply
put, Double variables hold numbers with decimal points.
Example: 123.56, 5.6, etc.
The syntax of the ‘Floating-Point Number or Double is as follows:
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
Previously, a different syntax was used to define the ‘Floating
Point Number or Double. Now let’s look at that syntax:
LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-
9]*)
EXPONENT_DNUM (({LNUM} | {DNUM}) [eE][+-]? {LNUM})
Example:
<?php
//TRIAL 1
$numeral = 216897510871;
$original_numeral = $numeral;
$numeral *= 11123.74;
$numeral /= 11123.74;
if ($original_numeral == $numeral) {
echo “Test 1: Value Equivalent<br />”;
}
else {
echo “Test 1: Value NOT Equivalent<br />”;
}
19
PHP
FUNDAMENTALS OF PHP II
//TRIAL 2
$numeral = 216897510871;
$original_numeral = $numeral;
$numeral *= 11123.75;
$numeral /= 11123.75;
if ($original_numeral == $numeral) {
echo “Test 2: Value Equivalent<br />”;
}
else {
echo “Test 2: Value NOT Equivalent<br />”;
}
?>
The output is as follows:
Test 1: Value Equivalent
Test 2: Value NOT Equivalent
String Literals:
We have already discussed that Strings hold both words and sentences.
These are always inserted within quotation marks. If it
starts with a single quotation mark then it must end with the
same. If a single quotation is inserted at the beginning of a string
then it can not be closed with a double quotation mark. If the quotation
marks are inserted in a code without any characters, then it
will be treated as ‘Null’ string. A numeric character is treated as a
string if it is inserted within quotation marks. For example, if the
number 9 is inserted in a PHP code, then it will be treated as a
number. On the other hand, if 9 is inserted in a PHP code, then it
will be treated as a string.
Example:
“It is an example of a string with double quotes”
‘It is an example of a string with single quotes’
“It is also an example of ‘a string’ where the
single quote will be ignored”
‘It is an example of “a string” where the double
quote will be ignored’
“4”
“ “ (Null string)
II
20
PHP
FUNDAMENTALS OF PHP
‘Here-docs’
‘Here-docs’ or ‘Here Documents’ is a special type of quoting that
enables you to quote a large block of text within a script. Here,
multiple print statements and quotation marks are not used. The
PHP engine treats this block of code as a double quoted statement.
‘Here-docs’ is extremely useful when a large block of HTML is used
in a PHP script. ‘Here-docs’ usually begin and end with a delimiter
word, a series of one or more characters that mark the border
between various sections in a data system. Numeric characters, letters
and underscores can be inserted in the delimiters. In PHP,
delimiters are written in capital letters. Three less than signs (<<<)
are inserted at the beginning of a delimiter (Example, <<<HEREDOCS).
Look at the following example:
Example:
print <<<LEARNING_HEREDOC_EXAMPLE
<text here>
...
< more text>
...
LEARNING_HEREDOC_EXAMPLE
Let’s look at the following example for better understanding:
Example:
<?php
$string = <<<EOD
Example of PHP heredoc stringing
across multiple lines of stringing
learning through example of using heredoc syntax.
EOD;
/* additional compound example, with variables.
*/
class foo
{
var $foo;
var $bar;
function foo()
21
PHP
FUNDAMENTALS OF PHP II
{
$this->foo = ‘Foo’;
$this->bar = array(‘Bar1’, ‘Bar2’,
‘Bar3’);
}
}
$foo = new foo();
$forename = ‘Jack’;
echo <<<EOT
My forename is “$forename”. I am printing $foo-
>foo.
Now, I am printing {$foo->bar[1]}.
This should print a capital ‘A’: \x41
EOT;
?>
The output of the above program is as follows:
My forename is “Jack”. I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital ‘A’: A
Now-docs
Now-doc is similar to Here-doc, and the only difference is that it is
a single quoted string while here-doc is a double quoted string.
Example:
<?php
$string = <<<’EOD’
Another example of stringing
across compound lines
by using nowdoc syntax.
EOD;
/* More compound example, with variables. */
class foo
{
public $foo;
public $bar;
function foo()
II
22
PHP
FUNDAMENTALS OF PHP
{
$this->foo = ‘Foo’;
$this->bar = array(‘Bar1’, ‘Bar2’,
‘Bar3’);
}
}
$foo = new foo();
$forename = ‘MyForename’;
echo <<<’EOT’
My forename is “$forename”. I am printing some
$foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital ‘A’: x41
EOT;
?>
The output of the above program is as follows:
My forename is “$forename”. I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital ‘A’: \x41
Escape Sequences:
In PHP, a single character, headed by a back slash (\), is an Escape
character. The HTML <pre> tag is used to display escape sequences
in the user’s browser. The PHP engine cannot interpret the escape
sequences without using the HTML<pre> tag.
Escape Sequences Functions
\” Used to print the next character as a double
quote, not as a string closer
\’ Used to print the next character as a single
quote, not a string closer
\n Used to print a new line character (remember
our print statements?)
\t Used to print a tab character
\r Used to print a carriage return
(not used very often)
\$ Used to print the next character as
a dollar, not as part of a variable
23
PHP
\\ Used to print the next character
as a backslash, not an escape character
Example:
<?php
$ExampleString = “It is an \”escpd\” string”;
$ExampleSingularString = ‘It \’will\’ act’;
$ExampleNonVariable = “I have \$zilch in
Example pocket”;
$ExampleNewline = “It ends with a line
return\n”;
$ExampleFile =
“c:\\windows\\system32\\Examplefile.txt”;
?>
Boolean literals:
Boolean literals return only two values: true and false. As discussed,
PHP is a case sensitive programming language. You can only use
the defined set of Boolean values like, yes/no, on/off, 1/0, etc.
Look at the syntax of the Boolean literals:
<?php
$foo = True; // assign the value TRUE to $foo
?>
Example:
<?php
// == is an operator which test
// equality and returns a Boolean value
if ($action == “display_version”) {
echo “The version is 1.23”;
}
// this is not necessary...
if ($display_dividers == TRUE) {
echo “<hr>\n”;
}
// ...as you can simply type
if ($display_dividers) {
echo “<hr>\n”;
}
?>
II
24
PHP
FUNDAMENTALS OF PHP
Null:
Null variable is assigned the ‘NULL’ value. A PHP engine will consider
a variable as NULL if you do not set it.
Array:
The Array variables hold multiple values. We will discuss ‘Array’ in
detail in the ‘Arrays in PHP’ section (Unit: 03).
Object:
Objects are used while working with the OOPs (Object Oriented
Programming Language). We will discuss object in detail in the
‘Object Orientation in PHP’ section.
Resource:
The Resource variables hold references to another external
resource like file handler, database object, etc.
2.3 Operators
In PHP, variables and values are performed by Operators, that is,
they operate on variables and values in PHP. Look at the following
expression:
$z = $x + $y;
In the above expression x and y are two numbers. It is clear
from the above expression that it would add x with y and the sum
is z. The plus sign (+) inserted between x and y is an operator
(Arithmetic Operator).
Operators used in PHP are categorically grouped in various sections:
1. Assignment Operators
2. Arithmetic Operators
3. Comparison Operators
4. String Operators
5. Combined Operators
Now let’s discuss in detail.
“ Assignment operators
You can use the Assignment Operator to assign a value to a variable.
Often a variable is assigned a value of another variable. In
this case assignment operators are used. The equal character (=) is
used here. Look at the following expression:
25
PHP
Example:
$first_var = 5;
$second_var = $first_var;
Here the values of both ‘$first_var’ and ‘$second_
var’ variables are assigned the same value i.e.
5.
Arithmetic operators
Look at the various Arithmetic Operators:
Operators Name Function
+ Addition This operator is used to add two values
- Subtraction This operator is used to subtract the
second value from the first one
* Multiplication This operator is used to multiply
two values
/ Division This operator is used to divide the first
value by the second value
% Modulus This operator is used to divide the first
value by the second value and it returns
only the remainder
Example 01:
$adding = 2 + 4;
$minus = 6 - 2;
$multiply = 5 * 3;
$divide = 15 / 3;
$percent = 5 % 2;
echo “Result adding: 2 + 4 = “.$adding.”<br />”;
echo “Result minus: 6 - 2 = “.$minus.”<br />”;
echo “Result multiply: 5 * 3 = “.$multiply.”<br
/>”;
echo “Result divide: 15 / 3 = “.$divide.”<br />”;
echo “Result percent: 5 % 2 = “ . $percent
The output of the above program is as follows:
Result adding: 2 + 4 = 6
Result minus: 6 - 2 = 4
Result multiply: 5 * 3 = 15
Result divide: 15 / 3 = 5
Result percent: 5 % 2 = 1.
II
26
PHP
FUNDAMENTALS OF PHP
Comparison operators
The ‘Comparison Operators’ verify the relationship between a variable
and its value. These operators are usually inserted within a
conditional statement and it returns boolean values like true and
false. Look at the various types of Comparison Operators:
Comparison Operators Name Function
= = Equal This operator is used to
check if the two variables
hold equal values.
= = = Identical This operator is used to
check whether two variables
hold equal values
and the data type of them
are also the same.
! = Not Equal This operator is used to
check if the two variables
hold unequal values.
! = = Not Identical This operator is used to
check for unequal values
and for the different data
types.
< Less than This operator is used to
check if the value of one
variable is lesser than
that of another.
> Greater than This operator is used to
check if the value of one
variable is greater than
that of another.
< = Less than This operator is used to
or Equal to check if the value of one
variable is less than or
equal to the value of
another variable.
> = Greater than This operator is used to
or Equal to check if the value of one
variable is greater than or
equal to the value of
another variable.
27
PHP
String operators
There are two types of ‘String Operators’: the Concatenating
Operator (‘.’) and the Concatenating Assignment Operator (‘.=’).
The Concatenating Operator joins the right and the left string into
a single string. The Concatenating Assignment Operators add the
argument that is placed on the right side of the equal operator
with the argument placed on the left side of the ‘equal’ operator.
Example:
$first_string = “Welcome”;
$second_string = “ Jack”;
$third_string = $first_string . $second_string;
echo $third_string . “!”;
The output of the above program is as follows:
Welcome Jack!
Combined operators
As the name suggests, the Combined Operators are the combinations
of different types of operators.
Look at the various types of Combined Operators:
Operator Name Example
+= Plus & Equals $a += 4;
-= Minus & Equals $a -= 6;
*= Multiply & Equals $a *= 4;
/= Divide & Equals $a /= 3;
%= Modulus & Equals $a %= 6;
.= Concatenation & Equals $example_str.=”Welcome”;
II
28
PHP