2. PHP Essentials 2
About This Book
This book is the PDF version of the online book “PHP Essentials”
at http://www.techotopia.com/index.php/PHP_Essentials
Techotopia is a library of free online IT books covering a wide range of topics including
operating systems, programming, scripting, system administration, databases, networking and much
more. The IT Essentials series of books are designed to provide detailed information that is
accessible to both experienced and novice readers. Each online book contains everything that is
needed to gain proficiency in the corresponding technology subject area.
Compiled as PDF by R. Prasath <prasath.ram8
@gmail.com >
Copyright 2007 Techotopia. All Rights Reserved.
3. PHP Essentials 3
Table of Contents
1. About PHP essentials........................................................................................................................7
Intended Audience..........................................................................................................................7
2. The History of PHP..........................................................................................................................8
The Creation of PHP.......................................................................................................................8
PHP 3 Hits the Big Time................................................................................................................8
PHP 4 Optimization, Scalability and More..................................................................................9
PHP 5 Object Orientation, Error Handling and XML .................................................................9
How Popular is PHP?......................................................................................................................9
3. An Overview of PHP......................................................................................................................10
How Does PHP Work?..................................................................................................................10
4. Creating a Simple PHP Script.........................................................................................................13
The PHP Code Delimiters.............................................................................................................13
Testing the PHP Installation..........................................................................................................13
Embedding PHP into an HTML File ...........................................................................................15
Embedding HTML into a PHP Script...........................................................................................16
5. Commenting PHP Code..................................................................................................................17
PHP Single Line Comments.........................................................................................................17
PHP Multiline Comments............................................................................................................18
6. An Introduction to PHP Variables.................................................................................................19
Naming and Creating a Variable in PHP.......................................................................................19
Assigning a Value to a PHP Variable............................................................................................19
Accessing PHP Variable Values...................................................................................................20
Changing the Type of a PHP Variable..........................................................................................21
Checking Whether a Variable is Set..............................................................................................21
Understanding PHP Variable Types..............................................................................................22
The PHP Integer Variable Type....................................................................................................22
The PHP Float Variable Type.......................................................................................................22
The PHP Boolean Variable Type..................................................................................................23
The PHP String Variable...............................................................................................................23
Extracting and Writing String Fragments.....................................................................................24
Creating PHP heredoc Strings .....................................................................................................25
8. PHP Constants................................................................................................................................26
Defining a PHP Constant..............................................................................................................26
Checking if a PHP Constant is Defined........................................................................................26
Using a Variable as a Constant Name ..........................................................................................27
Predefined PHP Constants ...........................................................................................................28
PHP Script and Environment Related Constants......................................................................28
PHP Mathematical Constants ......................................................................................................28
9. PHP Operators................................................................................................................................29
PHP Assignment Operators..........................................................................................................30
PHP Arithmetic Operators............................................................................................................30
PHP Mathematical Operators........................................................................................................31
4. PHP Essentials 4
PHP Comparison Operators..........................................................................................................32
PHP Logical Operators.................................................................................................................33
PHP Increment and Decrement Operators ...................................................................................34
PHP String Concatenation Operator.............................................................................................34
Concatenation of Numbers and Strings in PHP ...........................................................................35
PHP Execution Operator Executing Server Side Commands ....................................................36
10. PHP Flow Control and Looping....................................................................................................37
PHP Conditional Statements.........................................................................................................37
The PHP if ... else Statements ..................................................................................................38
PHP Looping Statements..............................................................................................................39
PHP for loops................................................................................................................................39
PHP while loops...........................................................................................................................40
PHP do ... while loops...............................................................................................................41
PHP switch Statements.................................................................................................................42
Breaking a Loop ..........................................................................................................................44
Breaking Out of Nested Loops .................................................................................................44
11. PHP Functions..............................................................................................................................45
What is a PHP Function?..............................................................................................................45
How to Write a PHP Function......................................................................................................45
Returning a Value from a PHP Function......................................................................................45
Passing Parameters to a PHP Function ........................................................................................46
Calling PHP Functions .................................................................................................................46
Passing Parameters by Reference..................................................................................................47
Returning Values by Reference ....................................................................................................48
Functions and Variable Scope ......................................................................................................49
12. PHP Arrays..................................................................................................................................50
Create a PHP Array.......................................................................................................................50
Accessing Elements in a PHP Array.............................................................................................51
Creating an Associative Array .....................................................................................................51
Accessing Elements of an Associative Array ...............................................................................51
Creating Multidimensional PHP Arrays ......................................................................................52
Accessing Elements in a Multidimensional PHP Array ..............................................................52
Using PHP Array Pointers ...........................................................................................................53
Changing, Adding and Removing PHP Array Elements .............................................................53
Looping through PHP Array Elements.........................................................................................54
Replacing Sections of an Array ...................................................................................................55
Sorting a PHP Array ....................................................................................................................55
Sorting Associative Arrays ..........................................................................................................56
Getting Information About PHP Arrays & other Array Functions ..............................................56
13. Working with Strings and Text in PHP.........................................................................................56
Changing the Case of a PHP String .............................................................................................56
Converting to and from ASCII Values .........................................................................................57
Printing Formatted Strings in PHP ..............................................................................................58
PHP printf Formatting Specifiers .............................................................................................58
5. PHP Essentials 5
Finding the Length of a PHP String ............................................................................................60
Converting a String into a PHP Array .........................................................................................60
Removing Leading and Trailing Whitespace from a PHP String ................................................61
Comparing Strings in PHP............................................................................................................61
String Comparison Functions Return Value ................................................................................62
Accessing and Modifying Characters in String ...........................................................................62
Searching for Characters and Substrings in a PHP String ...........................................................63
Extracting and Replacing Substrings in PHP ..............................................................................63
Replacing All Instances of a Word in a PHP String ....................................................................64
14. PHP, Filesystems and File I/O.......................................................................................................65
Opening and Creating Files in PHP .............................................................................................65
Closing Files in PHP ....................................................................................................................66
Writing to a File using PHP .........................................................................................................66
Reading From a File using PHP ...................................................................................................67
Checking Whether a File Exists ...................................................................................................68
Moving, Copying and Deleting Files with PHP ..........................................................................68
Accessing File Attributes .............................................................................................................68
PHP Output Buffering .................................................................................................................69
15. Working with Directories in PHP.................................................................................................70
Creating Directories in PHP ........................................................................................................70
Deleting a Directory ....................................................................................................................70
Finding and Changing the Current Working Directory ...............................................................70
Listing Files in a Directory ..........................................................................................................71
16. An Overview of HTML Forms.....................................................................................................71
Creating HTML Forms ................................................................................................................71
HTML Text Object .......................................................................................................................72
HTML TextArea Object ...............................................................................................................73
The HTML Button Object ...........................................................................................................73
HTML Check Boxes ....................................................................................................................74
HTML Radio Buttons ..................................................................................................................75
HTML Dropdown / Select Object ..............................................................................................76
HTML Password Object ..............................................................................................................77
17. PHP and HTML Forms.................................................................................................................77
Creating the Form ........................................................................................................................78
Processing Form Data Using PHP ...............................................................................................78
Processing Multiple Selections with PHP ...................................................................................80
18. PHP and Cookies Creating, Reading and Writing.....................................................................81
The Difference Between Cookies and PHP Sessions ...................................................................81
The Structure of a Cookie ............................................................................................................81
Cookie Expiration Setting ............................................................................................................82
Cookie path Setting ......................................................................................................................82
Cookie domain Setting .................................................................................................................82
Cookie Security Setting ...............................................................................................................82
6. PHP Essentials 6
Creating a Cookie in PHP ............................................................................................................82
Reading a Cookie in PHP ............................................................................................................83
Deleting a Cookie ........................................................................................................................83
19. Understanding PHP Sessions........................................................................................................83
What is a PHP Session? ...............................................................................................................83
Creating a PHP Session ...............................................................................................................84
Creating and Reading PHP Session Variables .............................................................................84
Writing PHP Session Data to a File .............................................................................................85
Reading a Saved PHP Session .....................................................................................................86
20. PHP Object Oriented Programming.............................................................................................86
What is an Object? .......................................................................................................................87
What is a Class? ...........................................................................................................................87
How is an Object Created from a Class? .....................................................................................87
What is subclassing?....................................................................................................................87
Defining a PHP Class ..................................................................................................................87
PHP Class Constructors and Destructors .....................................................................................88
Creating Members in a PHP Class ...............................................................................................88
Defining and Calling Methods .....................................................................................................89
Subclassing in PHP ......................................................................................................................91
PHP Object Serialization .............................................................................................................92
Getting Information about a PHP Object .....................................................................................94
21. Using PHP with MySQL..............................................................................................................94
Creating a MySQL User Account ................................................................................................94
Creating and Select MySQL Database ........................................................................................95
Creating a MySQL Database Table .............................................................................................95
Inserting Data into a MySQL Database Table .............................................................................96
Connecting with PHP to a MySQL Server ..................................................................................96
Selecting Records from a MySQL Database Using PHP ............................................................97
Adding Records to MySQL Database using PHP ........................................................................98
Modifying and Deleting MySQL Records using PHP .................................................................99
Using PHP to get Information about a MySQL Database ...........................................................99
22. PHP and SQLite..........................................................................................................................100
Creating an SQLite Database with PHP ....................................................................................100
Using PHP to Add Records to an SQLite Database ...................................................................101
Using PHP to Select Records from an SQLite Database ...........................................................101
7. PHP Essentials 7
1. About PHP essentials
Any attempt to gauge the popularity of PHP on the internet results in statistics which prove
difficult for the human mind to comprehend. As of April 2007 there were an estimated 20 million
unique web domains actively using PHP to generate and deliver content. While it is hard to
conceptualize 20 million web servers using PHP, it is not hard to infer from this number that PHP
has taken the web design and development community by storm since humble beginnings in 1995.
The purpose of this book is bring the power and ease of use of PHP to anyone with a desire
to learn PHP, and in doing so, join the tens of thousands of web developers who have already
discovered the flexibility and productivity that comes with using PHP.
The book is intended to cover all aspects of PHP. It begins by covering the history of PHP
before providing a high level overview of how PHP works and why it is so useful to web developers.
It then moves on to cover each area of PHP in detail, from the basics of the scripting language
through to object oriented programming, file and filesystem handling and MySQL and SQLite
database access. In addition, chapters are also provided covering the creation and handling of
HTML based forms and maintaining state using cookies and PHP sessions. All topics are
accompanied by extensive real world examples intended to bring theory to life.
Intended Audience
It is anticipated that the typical reader already has some web based experience at least in
terms of understanding the concepts of a web server and creating HTML based content. While prior
programming and scripting experience will be beneficial to the reader, this book is designed such
that even the nonprogrammer can quickly get up to speed with PHP.
8. PHP Essentials 8
2. The History of PHP
Every once in a while a person faces a particular problem or requirement to which there
appears to be no existing solution. Faced with this problem the person decides to create a solution
to provide the needed functionality.
Having developed the solution to their problem it then occurs to them that others may need
to solve the same problem, and they decide to make their solution freely available to others who, in
turn, can use and improve on it. Within a short period of time many people adopt the technology
and work on it, adding new features they feel will be useful. The solution soon grows beyond
expectations in terms of features and is adopted by more people than the original creator could ever
have imagined.
The Creation of PHP
The first version of what came to be known as PHP was created in 1995 by a man named
Rasmus Lerdof. Rasmus, now an engineer at Yahoo!, needed something to make it easier to create
content on his web site, something that would work well with HTML, yet give him power and
flexibility beyond what HTML could offer him. Essentially, what he needed was an easy way to
write scripts that would run on his web server both to create content, and handle data being passed
back to the server from the web browser. Using the Perl language, he created some technology that
gave him what he needed and decided to call this technology "Personal Home Page/Forms
Interpreter". The technology provided a convenient way to process web forms and create content.
The name "Personal Home Page/Forms Interpreter" was later shortened to PHP/FI and
eventually renamed to represent "PHP: Hypertext Preprocessor". The name is said to be recursive
because the full name also includes the acronym "PHP" an odd geeky joke that is common in
technology circles when people have trouble naming things. GNU is another recursive name that
represents "GNU's Not Unix".
PHP/FI version 1.0 was never really used outside of Rasmus' own web site. With the
introduction of PHP/FI 2.0 this began to change. When PHP 3 was released in 1997, adoption of
PHP exploded beyond all belief.
PHP 3 Hits the Big Time
By the time 1997 arrived the number of web sites on the internet was growing exponentially
and most of these web sites were being implemented using the Apache web server. It was around
this time that Andy Gutmans and Zeev Suraski launched the PHP 3 project, a project designed to
take PHP to the next level. One of the key achievements of the PHP 3 project was to implement
PHP as a robust Apache Module.
PHP 3 was implemented using a modular approach that made it easy for others to extend
functionality, and also introduced the first elements of objectorientation that would continue to
evolve through subsequent releases.
The combination of PHP 3 and Apache quickly lead to the widespread adoption of PHP, and
it is commonly estimated that, at its peak adoption level, PHP3 was used to power over 10% of all
web sites on the internet.
9. PHP Essentials 9
PHP 4 Optimization, Scalability and More
With PHP 4 Andi Gutmans and Zeev Suraski once again rearchitected PHP from the ground up.
PHP 4 was built upon a piece of technology called the Zend Engine. The move to the Zend Engine
brought about a number of key improvements in PHP:
• Support for other web servers (Microsoft's Internet Information Server (IIS) being of
particular significance).
• Improved memory handling to avoid memory leaks (one of the most difficult types of
problems to isolate in a program).
• Improved efficiency and performance to support large scale, complex, mission critical
enterprise application development using PHP.
In addition PHP 4 also built on the earlier Object Oriented Programming features of PHP 3 with the
introduction of classes.
PHP 5 Object Orientation, Error Handling and XML
The main, though far from only, feature of PHP 5 is the improved support for Object
Oriented Programming (OOP). In addition, PHP 5 introduced some features common in other
languages such as Java like try/catch error and exception handling.
PHP 5 also introduced new extensions aimed at easing the storage and manipulation of data.
Significant new features include SimpleXML for handling XML documents, and SQLite, an
embedded basic and easy to use database interface.
How Popular is PHP?
A quick review of some statistics gives a very clear indication of the phenomenally
widespread use of PHP. A company called Netcraft specializes in recording data about the types of
web servers and web server modules that are used on the internet. As of April 2007 Netcraft
reported that PHP was used on over 20,000,000 distinct web domains.
A web survey by SecuritySpace also lists PHP as the most widely deployed Apache module.
It is safe to say that PHP has taken the internet by storm.
10. PHP Essentials 10
3. An Overview of PHP
What Exactly is PHP?
PHP is an intuitive, server side scripting language. Like any other scripting language it
allows developers to build logic into the creation of web page content and handle data returned from
a web browser. PHP also contains a number of extensions that make it easy to interact with
databases, extracting data to be displayed on a web page and storing information entered by a web
site visitor back into the database.
PHP consists of a scripting language and an interpreter. Like other scripting languages, PHP
enables web developers to define the behavior and logic they need in a web page. These scripts are
embedded into the HTML documents that are served by the web server. The interpreter takes the
form of a module that integrates into the web server, converting the scripts into commands the
computer then executes to achieve the results defined in the script by the web developer.
How Does PHP Work?
To develop an understanding of how PHP works it is helpful to first explore what happens
when a web page is served to a user's browser.
When a user visits a web site or clicks on a link on a page the browser sends a request to the
web server hosting the site asking for a copy of the web page. The web server receives the request,
finds the corresponding web page file on the file system and sends it back, over the internet, to the
user's browser.
Typically the web server doesn't pay any attention to the content of the file it has just
transmitted to the web browser. As far as the web server is concerned the web browser understands
the content of the web page file and knows how to interpret and render it so that it appears as the
web designer intended.
Now let's consider what kind of web page content a web browser understands. These days a
web page is likely to consist of HTML, XHTML and JavaScript. The web browser contains code
that tells it what to do with these types of content. For example, it understands the structure HTML
in terms of rendering the page and it has a JavaScript interpreter built in that knows how to execute
the instructions in a JavaScript script. A web browser, however, knows absolutely nothing about any
PHP script that may be embedded in an HTML document. If a browser was served a web page
containing PHP it would not know how to interpret that code.
Given that a web browser knows nothing about PHP in a web page, then clearly something
has to be done with any PHP script in the page before it reaches the browser. This is where the PHP
preprocessing module comes in. The PHP module is, as mentioned previously, integrated into the
web server. The module tells the web server that when a page is to be served which contains PHP
script (identified by special markers) that it is to pass that script to the PHP preprocessing module
and wait for the PHP module to send it some content to replace that script fragment. The PHP
processing module understands PHP, executes the PHP script written by the web developer and,
based on the script instructions, creates output that the browser will understand. The web server
substitutes the content provided by the PHP preprocessor module in place of the PHP script in the
web page and sends it to the browser where it is rendered for the user to view.
11. PHP Essentials 11
To help understand this concept let's take a quick look at a before and after scenario. The
following HTML contains some PHP script that is designed to output an HTML paragraph tag:
<html>
<head>
<title>A PHP Example</title>
</head>
<body>
<?php
echo '<p>This line of HTML was generated by a PHP script embedded
into an HTML document</p>';
?>
</body>
</html>
The above example looks very much like standard HTML until you reach the part
surrounded by <?php and ?>. These are markers that designate where the embedded PHP script
begins and ends. When the web server finds this it sends it to the PHP module. The PHP module
interprets it, converts it to HTML and sends it back to the web server. The web server, in turn, sends
the following to the browser:
<html>
<head>
<title>A PHP Example</title>
</head>
<body>
<p>This line of HTML was generated by a PHP script embedded into an HTML
document</p>
</body>
</html>
Once loaded into the browser, it is rendered just like any other web page. The fact that the web page
originally contained PHP is completely transparent to the web browser.
The above example is certainly an oversimplification of the power of PHP. Some may
question why one would use PHP to output some static text that could have been achieved more
easily using an HTML tag. The fact is, however, HTML only makes sense if you know beforehand
exactly what needs to be displayed in the web page. Imagine instead, that you are developing an
online banking application. One of the pages you need to display must contain the customer's bank
account number combined with the current balance. Obviously this information is going to be
different for each customer. In this scenario you would develop an HTML page that essentially
serves as a template for the page, and then embed PHP into the page to extract the account and
balance information from a database. Once processed by the PHP module integrated into the web
server, this customer specific content will then appear in the HTML page in place of the PHP script
when the page is loaded into the browser.
12. PHP Essentials 12
Why is PHP so Useful?
In terms of web page content we have two extremes. At one extreme we have HTML which
is completely static. There is very little that can be done with HTML to create dynamic content in a
web page. At the other extreme we have scripting languages like JavaScript. JavaScript provides a
powerful mechanism for creating interactive and dynamic web pages.
When talking about JavaScript it is important to understand that it is, by design, a client side
scripting language. By this we mean that the script gets executed inside the user's browser and not
on the web server on which the web page originated. Whilst this is fine for many situations it is
often the case that by the time a script reaches the browser it is then either too late, or inefficient, to
do what is needed. A prime example of this involves displaying a web page which contains some
data from a database table. Since the database resides on a server (either the same physical server
which runs the web server or on the same network as the web server connected by a high speed fiber
network connection) it makes sense for any script that needs to extract data from the database to be
executed on the server, rather than waiting until it reaches the browser. It is for this kind of task that
PHP is perfectly suited. It is also fast and efficient (because the script is executed on the server it
gets to take advantage of multiprocessing, large scale memory and other such enterprise level
hardware features.
In addition to the advantages of being a server side scripting language PHP is easy to learn
and use. The fact that PHP works seamlessly with HTML makes it accessible to a broad community
of web designers.
Perhaps one of the most significant advantages of PHP to some is the ease with which it
interacts with the MySQL database to retrieve and store data.
13. PHP Essentials 13
4. Creating a Simple PHP Script
In the previous chapter we looked at how PHP works. No technology book would be
complete without including the obligatory simple example, and PHP Essentials is no exception to
this rule.
In this chapter we will look at constructing the most basic of PHP examples, and in so doing
we will take two approaches to creating PHP powered web content. Firstly we will look at
embedding PHP into an HTML page. Secondly, we will look at a reverse example whereby we
embed the HTML into the PHP. Both are perfectly valid approaches to using PHP.
The PHP Code Delimiters
The first thing to understand is the need to use PHP code delimiters to mark the areas of
PHP code within the web page. By default, the opening delimiter is <?php and the closing
delimiter is ?>. You can insert as many or as few blocks of PHP into a web page as you need as
long as each block is marked by the opening and closing delimiters.
<?php
echo '<p>This is a PHP script</p>';
?>
Testing the PHP Installation
Before embarking on even the simplest of examples, the first step on the road to learning
PHP is to verify that the PHP module is functioning on your web server. To achieve this, we will
create a small PHP script and upload it to the web server. To do this start up your favorite editor and
enter the following PHP code into it:
<?php
phpInfo();
?>
This PHP script calls the builtin PHP phpInfo() function, the purpose of which to output
information about the PHP preprocessing module integrated into your web server.
Save this file as phpInfo.php and upload it to a location on your web server where it will be
accessible via a web browser. Once you have done this open a browser and go to the URL for this
file.
If you do not see this information it is possible you do not have the PHP module integrated
into your web server. If you use a web hosting company, check with them to see if your particular
hosting package includes PHP support (sometimes PHP support is only provided with premium
hosting packages so you may need to upgrade). If you run your own web server consult the
documentation for your particular type of server (Apache, Microsoft IIS etc) for details on
integrating the PHP module. There are vastly superior resources available on the internet to assist in
installing PHP than we could never match in this book.
14. PHP Essentials 14
Embedding PHP into an HTML File
As you may have realized, by testing the PHP module on your web server you have already
crafted your first PHP script. We will now go on to create another script that is embedded into an
HTML page. Open your editor and create the following HTML file:
<html>
<head>
<?php
echo '<title>My First PHP Script</title>';
?>
</head>
<body>
<?php
echo '<p>This content was generated by PHP</p>';
?>
<p>And this content is static HTML</p>
</body>
</html>
Save this file as example.php and upload it to your web server. When you load this page into your
browser you should see something like the following:
15. PHP Essentials 15
Embedding HTML into a PHP Script
In the previous example we embedded some PHP Script into an HTML web page. We can
reverse this by putting the HTML tags into the PHP commands. The following example contains a
PHP script which is designed to output the HTML necessary to display a simple page. As with the
previous examples, create this file, upload it to your web server and load it into a web browser:
<?php
echo "<html>n";
echo "<head>n";
echo "<title>My Second PHP Example</title>n";
echo "</head>n";
echo "<body>n";
echo "<p>Some Content</p>n";
echo "</body>n";
echo "</html>n";
?>
When you load this into your browser it will be as if all that was in the file was HTML, and
if you use the view page source feature of your browser the HTML is, infact, all you will see. This is
because the PHP preprocessor simply created the HTML it was told to create when it executed the
script:
<html>
<head>
<title>My Second PHP Example</title>
</head>
<body>
<p>Some Content</p>
</body>
</html>
16. PHP Essentials 16
5. Commenting PHP Code
When programming in any language the process of adding comments involves writing notes
alongside the code to describe what the code does and how it works. The comments are ignored by
the PHP preprocessor when executing a script and are purely for human consumption.
Commenting of code is often neglected by software developers. Sometimes this is because
the code is being developed to meet a looming deadline and there is no time to adequately comment
it. Often there is a tendency on the part of the developers to believe that they will remember how the
code works six months or a year from now. Another common excuse for not commenting is that the
code is so well written as to be completely selfexplanatory.
Excuses aside, there is much to be gained from included helpful and concise comments with
the PHP code that powers your web site. Firstly, you will be amazed at how puzzling a section of
code can be even a few months after you have written it. It is not unusual for a developer to revisit
some old code they once wrote and express amazement that they actually wrote it. It is important to
remember that there is a good chance you will have to continue to maintain your PHP scripts long
after they are written.
Another important reason for commenting your code is to ensure that others who may follow
in your footsteps to maintain or add functionality to your creation will also benefit from reading
your comments. There are few things worse in the software development business than having to
traverse the steep learning curve caused by the complexity of somebody else's uncommented code.
Now that we have established that commenting code is worthwhile, we can take a look at the
mechanisms provided by PHP to achieve this goal. PHP provides two commenting mechanisms
one for single line comments, and another for multiline comments. PHP borrows its commenting
conventions from other languages such as C, C++ and Java, so if you are familiar with these
languages there will be no surprises here.
PHP Single Line Comments
Comments that reside on a single line are prefixed with the two forward slash characters in
PHP (i.e. //).
The following example contains a single line comment:
<?php
// This is a single line comment
?>
The single line comment can be on a line of its own, or it can be appended to the end of a line of
code:
<?php
echo "This is a test line"; // Output a line of text
?>
In the above example the PHP preprocessor will execute the echo statement and then ignore
everything after the // single line comment marker.
Single line comment markers are also useful for temporarily removing lines of code from the
17. PHP Essentials 17
execution flow (particularly useful during debugging sessions). For example, the following change
to our previous example will cause the PHP preprocessor to ignore the entire echo command during
execution:
<?php
// echo "This is a test line";
?>
PHP Multiline Comments
Multiline comments are wrapped in /* and */ delimiters. The /* marks the start of the
comment block and the */ marks the end. The following example demonstrates the use of multiline
commenting in PHP:
<?php
/*
This a multi-line block
of comments
*/
?>
Multiline comments are useful when you have notes you want to make in the code that will
take up more than one line. The ability to mark blocks of lines as comments avoids the necessity of
placing the single line comment marker at the start of each comment line.
Another useful application of multiline comments is to comment out blocks of PHP code
temporarily. It is quite common to have written some PHP script and then wonder if you can re
write it so that it is perhaps more efficient or reliable. In this situation you can comment out the old
script fragment so that it is no longer executed and write some new code. If it turns out your new
code is worse than the original (which happens from time to time) you can simply remove the new
code and uncomment the old to bring it back into the execution flow.
18. PHP Essentials 18
6. An Introduction to PHP Variables
When working with data values in PHP, we need some convenient way to store these values
so that we can easily access them and make reference to them whenever necessary. This is where
PHP variables come in.
Naming and Creating a Variable in PHP
Before learning how to declare a variable in PHP it is first important to understand some
rules about variable names (also known as variable naming conventions). All PHP variable names
must be prefixed with a $. It is this prefix which informs the PHP preprocessor that it is dealing
with a variable. The first character of the name must be either a letter or an underscore (_). The
remaining characters must comprise only of letters, numbers or underscores. All other characters are
deemed to be invalid for use in a variable name.
Let's look at some valid and invalid PHP variable names:
$_myName // valid
$myName // valid
$__myvar // valid
$myVar21 // valid
$_1Big // invalid - underscore must be followed by a letter
$1Big // invalid - must begin with a letter or underscore
$_er-t // invalid contains non alphanumeric character (-)
Variable names in PHP are casesensitive. This means that PHP considers $_myVariable to
be a completely different variable to one that is named ''$_myvariable”.
Assigning a Value to a PHP Variable
Values are assigned to variables using the PHP assignment operator. The assignment
operator is represented by the = sign. To assign a value to a variable therefore, the variable name is
placed on the left of the expression, followed by the assignment operator. The value to be assigned
is then placed to the right of the assignment operator. Finally the line, as with all PHP code
statements, is terminated with a semicolon (;).
Let's begin by assigning the word "Circle" to a variable named myShape:
$myShape = "Circle";
We have now declared a variable with the name myShape and assigned a string value to it of
"Circe". We can similarly declare a variable to contain an integer value:
$numberOfShapes = 6;
The above assignment creates a variable named numberOfShapes and assigns it a numeric
value of 6. Once a variable has been created, the value assigned to that variable can be changed at
any time using the same assignment operator approach:
19. PHP Essentials 19
<?php
$numberOfShapes = 6; // Set initial values
$myShape = "Circle";
$numberOfShapes = 7; // Change the initial values to new values
$myShape = "Square";
?>
Accessing PHP Variable Values
Now that we have learned how to create a variable and assign an initial value to it we now need to
look at how to access the value currently assigned to a variable. In practice, accessing a variable is
as simple as referencing the name it was given when it was created.
For example, if we want to display the value which we assigned to our numberOfShapes variable we
can simply reference it in our echo command:
<?php
echo "The number of shapes is $numberOfShapes.";
?>
This will cause the following output to appear in the browser:
The number of shapes is 6.
Similarly we can display the value of the myShape variable:
<?php
echo "$myShape is the value of the current shape.";
?>
The examples we have used for accessing variable values are straightforward because we
have always had a space character after the variable name. The question arises as to what should be
done if we need to put other characters immediately after the variable name. For example:
<?php
echo "The Circle is the $numberOfShapesth shape";
?>
What we are looking for in this scenario is output as follows:
The Circle is the 6th shape.
Unfortunately PHP will see the th on the end of the $numberOfShapes variable name as
being part of the name. It will then try to output the value of a variable called $numberOfShapesth,
which does not exist. This results in nothing being displayed for this variable:
The Circle is the shape.
Fortunately we can get around this issue by placing braces ({ and }) around the variable name to
20. PHP Essentials 20
distinguish the name from any other trailing characters:
<?php
echo "The Circle is the ${numberOfShapes}th shape";
?>
To give us the desired output:
The Circle is the 6th shape.
Changing the Type of a PHP Variable
As we mentioned at the beginning of this chapter, PHP supports a number of different
variable types (specifically integer, float, boolean, array, object, resource and string). We will look
at these types in detail in the next chapter (Understanding PHP Variable Types). First we are going
to look at changing the type of a variable after it has been created.
PHP is what is termed a loosely typed language. This contrasts with programming languages
such as Java which are strongly typed languages. The rules of a strongly typed language dictate that
once a variable has been declared as a particular type, its type cannot later be changed. In Java, for
example, you cannot assign a floating point number to a variable that was initially declared as being
a string.
Loosely typed languages such as PHP (and JavaScript), on the other hand, allow the variable
type to be changed at any point in the life of the variable simply by assigning a value of a different
type to it. For example, we can create a variable, assign it an integer value and later change it to a
string type by assigning a string to it:
<?php
$myNumber = 6; // variable is of integer type
$myNumber = "six"; // variable has now changed to string type
?>
The process of dynamically changing the type of a variable is known as automatic type conversion.
Checking Whether a Variable is Set
When working with variables it is often necessary to ascertain whether a variable actually
has a value associated with it or not at any particular point in a script. A mechanism is provided
with PHP to provide this ability through the isset() function. To test whether a variable has a value
set simply call the isset() function passing through the name of the variable as an argument (see
PHP Functions for details of passing through arguments to functions). The following code example
tests to see if a variable has a value or not and displays a message accordingly:
<?php
$myVariable = "hello";
if (isset($myVariable))
21. PHP Essentials 21
{
echo "It is set.";
}
else
{
echo "It is not set.";
}
?>
Understanding PHP Variable Types
In this chapter we will look at the PHP integer, string, float and boolean variable types.
Since the array and object types are slightly more complex entities we will devote subsequent
chapters to them later in the book (see PHP Arrays and PHP Object Oriented Programming).
The PHP Integer Variable Type
Integer variables are able to hold a whole number in the range of 2147483648 to
2147483647. Negative values can be assigned by placing the minus () sign after the assignment
operator and before the number. If the value assigned to an integer type variable moves outside the
supported range, either via assignment or mathematical calculation, the variable type is
automatically converted to a floating point type.
The following examples assign integers to variables:
<?php
$myInteger = 10;
$myNegative = -13457231;
?>
Integer values can be specified in Octal by prefixing the value with a zero '0':
$myoctInteger = 0456;
Similarly, hexadecimal values are pre-fixed with 0x:
$myHexInteger = 0x5EF3;
The PHP Float Variable Type
Floating point variables contain numbers that require the use of decimal places. In addition,
float variables can store whole numbers up to higher values than the integer variable type (such as
1.067, 0.25, 423454567098, 84664435.9576). Floating point variable creation and initialization
examples are as follows:
22. PHP Essentials 22
<?php
$myFloat = 9234.98;
$myOtherFloat = 9547894367.987483701
?>
The PHP Boolean Variable Type
PHP boolean type variables hold a value of true or false and are used to test conditions such
as whether some part of a script was performed correctly. We will look at using boolean values in
greater detail when we look at PHP Flow Control and Looping, with particular regard to the if
statement. It is useful to know that the true and false values are actually represented internally by
PHP boolean values 1 and 0 respectively, though it is important to be aware that boolean 1 and 0 are
not the same as integer values 1 and 0.
The PHP String Variable
The string variable type is used to hold strings of characters such as words and sentences. In
addition to providing mechanisms for creating and changing entire string variable values, PHP
allows you to extract and change parts of a string value.
A string can be assigned to variable either by surrounding it in single quotes (') or double
quotes ("). If your string itself contains either single or double quotes you should use the opposite to
wrap the string:
<?php
$myString = "A string of text";
$myString2 = 'Another string of text';
$myString3 = "This string contains 'single quotes'";
$myString4 = 'This string contains "double quotes"';
?>
You can also escape quotes in your string by preceding them with a backslash (), especially
useful if your string contains both single and double quotes of its own that would otherwise confuse
the PHP pre-processor:
<?php
$myString3 = 'This string contains 'single quotes'';
$myString4 = "This string contains "double quotes" and 'single
quotes'";
?>
23. PHP Essentials 23
Double quoted strings also allow the insertion of special control sequences that are
interpreted to have special meaning for the PHP preprocessor (such as a tab or new line). The
following table outlines the various control sequences and their respective descriptions:
Control Sequence Description
n New line
r Carriage Return
t Tab
Backslash Character
" Double quotation mark
$ Dollar sign (prevents text from being treated as a variable name)
034 Octal ASCII value
x0C Hexadecimal ASCII Value
As an example, we can declare a string variable which contains a tab and a new line character as
follows:
<?php
$myString = "This is a line of Textnandthis is another line with a tab
here t for us.";
?>
Extracting and Writing String Fragments
Once we have defined a string variable we can extract or make changes to individual
characters in the string using what is termed {x} notation, where x represents the index into the
string of the character we wish to view or change. Before we look at an example, it is important to
keep in mind that the index into the string is zero based. By this we mean that the first character of
the string is in position 0, not position 1. For example, to change the first and last characters of a
string variable:
<?php
$myString = "My Bug";
$myString{0} = "m";
$myString(5] = "s";
echo $myString;
?>
The result of the above script will change the string from:
My Bug
to:
my Bus
24. PHP Essentials 24
Creating PHP heredoc Strings
The PHP heredoc string syntax allows free form text to be used without having to worry
about escaping special characters such as quotes and backslashes. The content of the heredoc string
is wrapped with <<<EOD and EOD; markers.
The only rules are that the closing EOD; must be at the beginning of the last line, and the only
content on that line, as follows:
<?php
$myString = <<<EOD
This is some free form text. It can span mutliple
lines and can contain otherwise troublesome characters like
and " and ' without causing any problems.
EOD;
echo $myString;
?>
25. PHP Essentials 25
8. PHP Constants
Constants are particularly useful for defining a value that you frequently need to refer to that
does not ever change. For example, you might define a constant called INCHES_PER_YARD that
contains the number of inches in a yard. Since this is a value that typically doesn't from one day to
the next it makes sense to define it as a constant. Conversely, a value that is likely to change, such as
the Dollar to Yen exchange rate is best defined as a variable.
PHP constants are said to have global scope. This basically means that once you have
defined a constant it is accessible from any function or object in your script.
In addition, PHP provides a number of builtin constants that are available for use to make
life easier for the PHP developer.
Defining a PHP Constant
Rather than using the assignment operator as we do when defining variables, constants are
created using the define() function. Constants also lack the $ prefix of variable names.
The define function takes two arguments, the first being the name you wish to assign to the
constant, and the second the value to assign to that name.
Constant names are case sensitive. Although it is not a requirement, convention carried over from
other programming languages suggests that constants should be named in all upper case characters.
The following example demonstrates the use of the define() function to specify a constant:
<?php
define('INCHES_PER_YARD', 36);
?>
Once defined the constant value can be accessed at any time just by referring to the name. For
example, if we define a string constant as follows:
<?php
define('WELCOME_MESSAGE', "Welcome to my World");
?>
we can subsequently access that value anywhere in our script. For example, to display the value:
echo WELCOME_MESSAGE;
Checking if a PHP Constant is Defined
It can often be useful to find out if a constant is actually defined. This can be achieved using
the PHP defined() function. The defined() function takes the name of the constant to be checked as
an argument and returns a value of true or false to indicate whether that constant exists.
For example, let's assume we wish to find out if a constant named MY_CONSTANT is defined. We
can simply call the defined() function passing through the name, and then test the result using an
if .. else statement (see PHP Flow Control and Looping for more details on using if .. else):
26. PHP Essentials 26
<?php
define ('MY_CONSTANT', 36);
if (defined('MY_CONSTANT'))
{
echo "Constant is defined";
}
else
{
echo "Constant is not defined";
}
?>
Using a Variable as a Constant Name
It is not always the case that you want to hardcode a constant name into a script at the point
you wish to access it. For example, you may have a general purpose script that you wish to perform
tasks on any number of different constants, not just one that you happen to have typed in the name
for. The best way to resolve this issue is store the name of the constant in a variable. How then,
would you access the value assigned to that constant? The answer is to use the PHP constant()
function. The constant() function takes the name of the constant as an argument and returns the
value of the constant which matches that name.
The key point to understand here as that the argument passed through to constant() can be a string
variable set to the name of the constant.
As always an example helps a great deal in understanding a concept. In the script below we
define a constant called MY_CONSTANT. Next, we create a string variable called constantName and
assign it a value of MY_CONSTANT (i.e. a string that matches the constant name). We can then use
this new variable as the argument to constant() to obtain the constant value of MY_CONSTANT:
<?php
define ('MY_CONSTANT', "This is a constant string.");
$constantName = 'MY_CONSTANT';
if (defined ( $constantName ))
{
echo constant($constantName);
}
else
{
echo "$constantName constant is not defined.";
}
?>
The above script will display the constant value if it exists by using the value of the $constantName
variable constant name key.
27. PHP Essentials 27
Predefined PHP Constants
As we mentioned briefly at the start of this chapter, PHP provides a number of builtin
constants that can be of significant use to the PHP web developer. In this section we will look at
some of the more useful constants available.
PHP Script and Environment Related Constants
The following constants provide information about the script which is currently executing,
and also the environment in which the PHP web server module is running. These are of particular
use when debugging scripts:
Constant Name Description
Contains the number of the line in the current PHP file (or include file)
__LINE__
which is being currently being executed by the PHP preprocessor.
Contains the name of the file or include which contains the currently
__FILE__
executing line of PHP code.
__FUNCTION__ Contains the name of the PHP function which is currently executing
__CLASS__ Contains the class which is currently in use
Contains the name of the method in the current class which is currently
__METHOD__
executing
PHP_VERSION Contains the version of PHP that is executing the script
PHP_OS Contains of the name of the Operating System hosting the PHP Pre
processor
Contains the Newline character for the host OS (differs between
PHP_EOL
UNIX/Linux and Windows for example)
DEFAULT_INCLUDE
The default path where PHP looks for include files
_PATH
PHP Mathematical Constants
PHP provides a number of useful mathematical constants that can be used to save both
programming time when writing a script, and processing time when performing calculations in a
script. The following table provides a list of the mathematical constants available in PHP:
Constant Description
M_E Value of e
M_EULER Value of Euler's constant
M_LNPI The natural logarithm of PI
M_LN2 The natural logarithm of 2
M_LN10 The natural logarithm of 10
M_LOG2E Value of base2 logarithm of E
M_LOG10E The base10 logarithm of E
28. PHP Essentials 28
M_PI The value of PI
M_PI_2 The value of PI/2
M_PI_4 The value of PI/4
M_1_PI The value of 1/PI
M_2_PI The value of 2/PI
M_SQRTPI The square root of PI
M_2_SQRTPI The value 2/square root of PI
M_SQRT2 The square root of 2
M_SQRT3 The square root of 3
M_SQRT1_2 The square root of 1/2
9. PHP Operators
Operators in PHP, and any other programming language for that matter, enable us to
perform tasks on variables and values such as assign, multiply, add, subtract and concatenate them.
Operators take the form of symbols (such as + and ) and combinations of symbols (such as ++ and
+=).
Operators in PHP work with operands which specify the variables and values that are to be
used in the particular operation. The number and location of these operands in relation to the
operators (i.e. before and/or after the operator) depends on the type of operator in question. Let's
take, for example, the following simple expression:
1 + 3;
In this expression we have one operator (the '+') and two operands (the numbers 1 and 3).
The '+' operator adds the values of two operands (resulting in a value of 4).
Operators can be combined to create complete expressions:
$myVar = 1 + 3;
In the above example, the assignment operator (=) assigns the result of the addition to the
operand represented by the variable $myVar. After evaluating this expression the value of 4 will
have been assigned to the variable $myVar.
In this chapter of PHP Essentials we will explore each type of operator and explain how they are
used in relation to their operands.
29. PHP Essentials 29
PHP Assignment Operators
We briefly covered the basic PHP assignment operator in the An Introduction to PHP
Variables chapter. We will now look at this and other assignment operators in more detail.
The assignment operator is used to assign a value to a variable and is represented by the
equals (=) sign. The assignment operator can also be combined with arithmetic operators to
combine an assignment with a mathematical operation (for example to multiply one value by
another and assigning the result to the variable) and also to perform string concatenations.
The following table lists the seven assignment operators available in PHP, together with descriptions
and examples of their use:
Operator Type Description Example
Sets the value of the left hand operand
= Assignment $myVar = 30;
to the value of the right
Adds the value of left hand operand to
$myVar = 10;
+= AdditionAssignment the value of the right hand operand and
$myVar += 5;
assigns result to left hand operand
Subtracts the value of right hand
operand from the value of the left hand $myVar = 10;
= SubtractionAssignment
operand and assigns result to left hand $myVar = 5;
operand
Multiplies the left hand operand by
$myVar = 10;
*= MultiplicationAssignment value of the right hand operand
$myVar *= 5;
assigning result to left hand operand
Divides the left hand operand by value
$myVar = 10;
/= DivisionAssignment of the right hand operand assigning
$myVar /= 5;
result to left hand operand
Sets the value of the left hand operand
$myVar = 10;
%= ModuloAssignment to the remainder of the value after being
$myVar %= 5;
divided by the right hand operand
Sets the value of the left hand operand $sampleString="M
to a string containing a concatenation of y color is ";
.= ConcatenationOperand
its value appended with the string in the $sampleString .=
right hand operand "blue";
PHP Arithmetic Operators
As the name suggests PHP arithmetic operators provide a mechanism for performing mathematical
operations:
30. PHP Essentials 30
Operator Type Description Example
Sets the value of the left hand operand
= Assignment $myVar = 30;
to the value of the right
Adds the value of left hand operand to
$myVar = 10;
+= Addition-Assignment the value of the right hand operand and
$myVar += 5;
assigns result to left hand operand
Subtracts the value of right hand
operand from the value of the left hand $myVar = 10;
-= Subtraction-Assignment
operand and assigns result to left hand $myVar -= 5;
operand
Multiplies the left hand operand by
$myVar = 10;
*= Multiplication-Assignment value of the right hand operand
$myVar *= 5;
assigning result to left hand operand
Divides the left hand operand by value
$myVar = 10;
/= Division-Assignment of the right hand operand assigning
$myVar /= 5;
result to left hand operand
Sets the value of the left hand operand
$myVar = 10;
%= Modulo-Assignment to the remainder of the value after being
$myVar %= 5;
divided by the right hand operand
Sets the value of the left hand operand $sampleString="M
to a string containing a concatenation of y color is ";
.= Concatenation-Operand
its value appended with the string in the $sampleString .=
right hand operand "blue";
PHP Mathematical Operators
As the name suggests PHP arithmetic operators provide a mechanism for performing mathematical
operations:
Operator Type Description Example
$total = 10 +
+ Addition Calculates the sum of two operands
20;
Subtraction Calculates the difference between two operands $total = 10 20;
$total = 10 *
* Multiplication Multiplies two operands
20;
/ Division Divides two operands $total = 10 / 20;
Returns the remainder from dividing the first operand
% Modulus $total = 20%10;
by the second
$var = 1 + 2; // Sets variable $var to the sum of 1 + 2
$var = 3 % 7; // Sets variable $var to the modulus of 3 and 7
$var = 10;
31. PHP Essentials 31
$var2 = $var / 2; // Sets variable $var2 to the value of 10 divided by 2
PHP Comparison Operators
The comparison operators provide the ability to compare one value against another and
return either a true or false result depending on the status of the match. For example, you might use
a comparison operator to check if a variable value matches a particular number, or whether one
string is identical to another. PHP provides a wide selection of comparison operators for just about
every comparison need.
The comparison operators are used with two operands, one to the left and one to the right of the
operator. The following table outlines the PHP comparison operators and provides brief descriptions
and examples:
Operator Type Description Examples
$myVar = 10;
Returns true if first operand equals
== Equal to if ($myVar == 10)
second
echo 'myVar equals 10';
$myVar = 10;
Returns true if first operand is not
!= Not equal to if ($myVar != 20)
equal to second
echo 'myVar does not equal 10';
$myVar = 10;
Returns true if first operand is not
<> Not equal to if ($myVar <> 20)
equal to second
echo 'myVar does not equal 10';
$myVar = 10;
$myString="10";
Returns true if first operand equals
=== Identical to if ($myVar === $myString)
second in both value and type
echo 'myVar and myString are same
type and value';
$myVar = 10;
Returns true if first operand is not $myString="10";
Not identical
!== identical to second in both value and if ($myVar !== $myString)
to
type echo 'myVar and myString are not
same type and value';
$myVar = 10;
Returns true if the value of the first
< Less than if ($myVar < 20)
operand is less than the second
echo 'myVar if less than 20';
$myVar = 10;
Returns true if the value of the first
> Greater than if ($myVar > 5)
operand is greater than the second
echo 'myVar if greater than 5';
$myVar = 10;
Returns true if the value of the first
Less than or if ($myVar <= 5)
<= operand is less than, or equal to, the
equal to echo 'myVar is less than or equal to
second
5';
32. PHP Essentials 32
$myVar = 10;
Returns true if the value of the first
Greater than if ($myVar >= 5)
>= operand is greater than, or equal to,
or equal to echo 'myVar is greater than or equal
the second
to 5';
PHP Logical Operators
Logical Operators are also known as Boolean Operators because they evaluate parts of an
expression and return a true or false value, allowing decisions to be made about how a script should
proceed. The logical operators supported by PHP are listed in the following table:
Operator Type Description Examples
if (($var1 < 25) && ($var2 >
&& AND Performs a logical "AND" operation.
45))
|| OR Performs a logical "OR" operation. if (($var1 < 25) || ($var2 > 45))
Performs a logical "XOR" (exclusive OR) if (($var1 < 25) xor ($var1 >
xor XOR
operation. 45))
The first step to understanding how logical operators work is to construct a sentence rather than to
look at a script example right away. Let's assume we need to check some aspect of two variables
named $var1 and $var2. Our sentence might read:
If $var1 is less than 25 AND $var2 is greater than 45 display a message.
Here the logical operator is the "AND" part of the sentence. If we were to express this in
PHP we would use the comparison operators we covered earlier together with the && logical
operator:
if (($var1 < 25) && ($var2 > 45))
echo 'Our expression is true';
Similarly, if our sentence was to read:
If $var1 is less than 25 OR $var2 is greater than 45 display a message.
Then we would replace the "OR" with the PHP equivalent ||:
if (($var1 < 25) || ($var2 > 45))
echo 'Our expression is true';
Another useful logical operator is the Exclusive Or (XOR) operator. The XOR operator returns true
if only one of the expressions evaluates to be true. For example:
If $var is EITHER less than 25 OR greater than 45 display a message
We represent XOR with the keyword xor:
if (($var1 < 25) xor ($var1 > 45))
echo 'Our expression is true';
The final Logical Operator is the NOT operator which simply inverts the result of an expression.
The ! character represents the NOT operator and can be used as follows:
33. PHP Essentials 33
(10 > 1) // returns ''true''
!(10 > 1) // returns ''false'' because we have inverted the result
with the logical NOT
PHP Increment and Decrement Operators
When programming in any language it is not uncommon to need to increment or decrement the
value stored in a variable by 1. This could be done long hand:
$myVar = $myVar-1;
A much quicker way, however, is to use the PHP increment and decrement operators. These
consist of the operators ++ (to increment) and (to decrement) combined with an operand (the
name of the variable to which the change is to be applied).
There are two ways of using these operators, pre and post. The pre mode performs the
increment or decrement before performing the rest of the expression. For example, you might want
to increment the value of a variable before it is assigned to another variable, or used in a calculation.
In the post mode the increment or decrement is performed after the expression has been performed.
In this instance, you might want the value to be decremented after it has been assigned or used in a
calculation.
Whether a pre or post is used depends on whether the operator appears before (for pre), or
after (for post) the variable name in the expression. For example $myVariable or $myVariable++.
The following table outlines the various forms of pre and post increment and decrement operators,
together with examples that show how the equivalent task would need to be performed without the
increment and decrement operators.
Operator Type Description Equivalent
$var = 10;
Increments the variable value before it is used in rest of
++$var Preincrement $var2 = $var +
expression
1;
Decrements the variable value before it is used in rest $var = 10;
$var Predecrement
of expression $var2 = $var 1;
$var = 10;
Increments the variable value after it is used in rest of
$var++ Postincrement $var2 = $var;
expression
$var = $var + 1;
$var = 10;
Decrements the variable value after it is used in rest of
$var Postdecrement $var2 = $var;
expression
$var = $var 1;
PHP String Concatenation Operator
The PHP String concatenation operator is used to combine values to create a string. The
concatenation operator is represented by a period/full stop (.) and can be used to build a string from
other strings, variables containing nonstrings (such as numbers) and even constants:
34. PHP Essentials 34
We will start with the operator in its simplest form concatenating two strings:
echo 'My favorite color is ' . 'blue.';
The above example will display a string that is the result of second string appended to the end of the
first string:
=> My favorite color is blue.
The string concatenation operator can also be used with variables. In the following example the
value of the $myString variable is appended to the end of the string:
$myString = "red";
echo 'My favorite color is ' . $myString;
We can also reference constants (see PHP Constants for details on using constants in PHP) when
using concatenation:
define (MY_COLOR, "Green");
echo 'My favorite color is ' . MY_COLOR;
The above example will result in the following output:
My favorite color is Green
Concatenation of Numbers and Strings in PHP
We mentioned at the beginning of this section that it is also possible to mix numbers and strings in a
concatenation operation to create strings. For example we can include the number 6 in our string as
follows:
echo 6 . ' is my lucky number';
The above example will create output as follows:
6 is my lucky number
We can also perform a calculation and have the result included in the concatenation:
echo 6 + 5 . ' is my lucky number'
In this example the mathematical operation will be evaluated before the concatenation, thereby
producing:
11 is my lucky number
It is important to note an issue when dealing with strings and numbers. While the above works fine
because we began the expression with the addition, something very different happens when we have
the addition after the string: