Description
With PHP for the World Wide Web, Fourth Edition: Visual QuickStart Guide, readers can start from the beginning to get a tour of the programming language, or look up specific tasks to learn just what they need to know. This task-based visual reference guide uses step-by-step instructions and plenty of screenshots to teach beginning and intermediate users this popular open-source scripting language. Leading technology author Larry Ullman guides readers through the latest developments including use and awareness of HTML5 with PHP. Other addressed changes include removal of outdated functions and more efficient ways to tackle common needs. Both beginning users, who want a thorough introduction to the technology, and more intermediate users, who are looking for a convenient reference, will find what they need here–in straightforward language and through readily accessible examples.
Open the PDF directly: View PDF link";
One workaround is to
escape
the quota-
tion marks within the HTML by preceding
them with a backslash [
\
]:
print "link";
By escaping each quotation mark within
the
statement, you tell PHP to print
the mark itself instead of treating the quo-
tation mark as either the beginning or the
end of the string to be printed.
To send HTML to the browser:
1. Open the
hello1.php
script [Script 1.3]
in your text editor or IDE, if it is not
already open.
2. Within the HTML head, declare a CSS
class [Script 1.4]:
.bold {
font-weight: bolder;
}
continues on next page
A Attempting to print double quotation marks will
create errors, because they conflict with the
statement’s primary double quotation marks.
Script 1.4 Using
, you can send HTML
tags along with text to the browser, where the
formatting will be applied.
1
2
3
4
5 Hello, World!
6
7 .bold {
8 font-weight: bolder;
9 }
10
11
12
13
The following was created by PHP:
14
17
18
19
ptg18144795
22 Chapter 1
This CSS code declares a class named
bold
, which will be used to add empha-
sis to text. This is obviously a fairly trivial
use of CSS, but by declaring this as a
class, it can easily be updated, perhaps
to change the color of the text or the
size, along with its weight.
3. Edit the
Hello, world!
message by
adding HTML tags, making it read as
follows:
print "
➝
Hello, world!";
To make the PHP-generated part of
the message stand out, CSS styling will
bold the greeting. For this to work, you
must escape the quotation marks within
the span tag so they don’t conflict with
the
statement’s quotation mark.
4. Save the script as
hello2.php
, place
it on your PHP-enabled server, and run
the page in your browser B.
B The new version of the
Hello, world!
page, with
a little more decoration and appeal.
Using White Space
When programming in PHP, white space is generally [but not universally] ignored. Any blank line
[just one or several in a row] in PHP code is irrelevant to the end result. Likewise, tabs and spaces
are normally inconsequential to PHP. And because PHP code is not visible in the browser [unless
there’s a problem with the server], white space in your PHP files has no impact on what the end
user sees.
The spacing of HTML code shows up in the HTML source of a web page but has only a minimal
effect on what’s viewed in the browser. For example, all of a page’s HTML source code could be
placed on one line without changing what the end user sees. If you had to hunt for a problem in
the HTML source, however, you would not like the long, single line of HTML.
You can affect the spacing of dynamically generated HTML code by printing it in PHP over multiple
lines, or by using the newline character [
\n
] within double quotation marks:
print "Line 1\nLine 2";
Again, use of the newline character affects the
HTML source code
of the web page, not what the
end user sees rendered in the browser.
To adjust the spacing in the rendered web page, you’ll use CSS, plus paragraph, div, and break
tags, among others.
ptg18144795
Getting Started with PHP 23
Understanding the role of quotation
marks and how to escape problematic charac-
ters is crucial to programming with PHP. These
topics will be covered in more detail in the
next two chapters.
The HTML you send to the web browser
from PHP doesn’t need to be this simple. You
can create tables, JavaScript, and much, much
more.
Remember that any HTML outside the
PHP tags will automatically go to the browser.
Within the PHP tags,
statements are
used to send HTML to the web browser.
C The resulting HTML source code of
hello2.php
B.
5. View the HTML page source to see the
code that was sent to the browser C.
How you do this depends on the
browser: Select View > Developer >
View Source in Chrome, View > Page
Source in Firefox, or View > Source in
Internet Explorer.
This is a step you’ll want to be in the
habit of taking, particularly when prob-
lems occur. Remember that PHP is
primarily used to generate HTML, sent
to and interpreted by the browser.
Often, confirming what was sent to the
browser [by viewing the source] will help
explain the problem you’re seeing in the
browser’s interpretation [or visible result].
ptg18144795
24 Chapter 1
Adding Comments
to Scripts
Comments are integral to programming,
not because they do anything but because
they help you remember why
you
did
something. The computer ignores these
comments when it processes the script.
Furthermore, PHP comments are never
sent to the browser, remaining your secret.
PHP supports three ways of adding
comments. You can create a single-line
comment by putting either
//
or
#
at the
beginning of the line you want ignored:
// This is a comment.
You can also use
//
or
#
to begin a com-
ment at the end of a PHP line, like so:
print "Hello"; // Just a greeting.
Although it’s largely a stylistic issue,
//
is
much more commonly used in PHP than
#
.
You can create a multiline comment using
/*
to begin the comment and
*/
to con-
clude it:
/* This is a
multi-line comment. */
Some programmers prefer this comment
style because it contains both open and
closing “tags,” providing demarcation for
where the comment begins and ends.
ptg18144795
Getting Started with PHP 25
To add comments to a script:
1. Open the
hello2.php
created earlier
[Script 1.4] in your text editor or IDE.
2. After the initial PHP tag, add some
comments to your script [Script 1.5]:
/*
* Filename: hello3.php
* Book reference: Script 1.5
* Created by: Larry Ullman
*/
This is just a sample of the kind of
comments you can write. You should
document what the script does, what
information it relies on, who created it,
when, and so forth. Stylistically, such
comments are often placed at the top
of a script [as the first thing within the
PHP section, that is], using formatting
like this. The extra asterisks aren’t
required; they just draw attention to
the comments.
3. On line 21, in front of the
state-
ment, type
//
.
By preceding the
statement with
two slashes, you ensure that the func-
tion call is “commented out,” meaning it
will never be executed.
4. After the closing PHP tag [on line 23],
add an HTML comment:
This line of code will help you distin-
guish among the different comment
types and where they appear. This com-
ment will appear only within the HTML
source code.
continues on next page
Script 1.5 PHP and HTML comments are added
to the script to document it and to render a line of
PHP code inert.
1
2
3
4
5 Hello, World!
6
7 .bold {
8 font-weight: bolder;
9 }
10
11
12
13
The following was created by PHP:
14
24
25
26
27
ptg18144795
26 Chapter 1
5. Save the script as
hello3.php
, place
it on your PHP-enabled server, and run
the page in your web browser A.
6. View the source of the page to see the
HTML comment B.
You can comment out just one line of
code or several using the
/*
and
*/
method.
With
//
or
#
, you can negate only one line at
a time.
Different programmers prefer to com-
ment code in different ways. The important
thing is to find a system that works for you
and stick to it.
Note that you cannot use HTML com-
ment characters [
] within PHP to
comment out code. You could have PHP print
those tags to the browser, but in that case
you’d create a comment that appeared in the
HTML source code on the client’s computer
[but not in the browser window]. PHP comments
never make it as far as a user’s computer.
Despite my strong belief that you can’t
over-comment your scripts, the scripts in this
book aren’t as documented as they should
be, in order to save space. But the book will
document each script’s name and number, for
cross-reference purposes.
When you change a script’s code, be
certain to update its comments as well. It’s
quite confusing to see a comment that suggests
a script or a line of code does something other
than what it actually does.
A With the
statement commented out,
the page looks just as it would if the
call
weren’t there.
B HTML comments don’t appear in the web
browser but are in the HTML source. PHP
comments remain in the PHP script on the server,
not visible inside the HTML source.
ptg18144795
Getting Started with PHP 27
Basic Debugging Steps
Debugging is by no means a simple con-
cept to grasp, and unfortunately, it’s one
that is only truly mastered by doing. The
next 50 pages could be dedicated to the
subject and you’d still merely pick up a
fraction of the debugging skills that you’ll
eventually acquire and need.
The reason I introduce debugging in this
harrowing way is that it’s important not to
enter into programming with delusions.
Sometimes code won’t work as expected,
you’ll inevitably create careless errors, and
some days you’ll want to pull your hair out,
even when using a comparatively user-
friendly language such as PHP. In short,
prepare to be perplexed and frustrated
at times
. I’ve been coding in PHP since
1999, and occasionally I still get stuck in
the programming muck. But debugging is
a very important skill to have, and one that
you will eventually pick up out of necessity
and experience. As you begin your PHP
programming adventure, I offer the follow-
ing basic but concrete debugging tips.
ptg18144795
28 Chapter 1
To debug a PHP script:
n
Make sure you’re always running PHP
scripts through a URL!
This is perhaps the most common
beginner’s mistake. PHP code must be
run through the web server applica-
tion, which means it must be requested
through //
something
. When you
see actual PHP code instead of the
result of that code’s execution, most
likely you’re not running the PHP script
through a URL.
n
Know what version of PHP you’re
running.
Some problems arise from the version
of PHP in use. Before you ever use
any PHP-enabled server, run the
phpinfo.php
file [Script 1.2] to confirm
the version of PHP in use.
n
Make sure
display_errors
is on.
This is a basic PHP configuration set-
ting [discussed in Appendix A]. You
can confirm this setting by executing
the
phpinfo[]
function [just use your
browser to search for
display_errors
in the resulting page]. For security
reasons, PHP may not be set to display
the errors that occur. If that’s the case,
you’ll end up seeing blank pages when
problems occur. To debug most prob-
lems, you’ll need to see the errors, so
turn this setting on while you’re learn-
ing. You’ll find instructions for doing so
in Appendix A and Chapter 3, “HTML
Forms and PHP.”
n
Check the HTML source code.
Sometimes the problem is hidden in
the HTML source of the page. In fact,
sometimes the PHP error message can
be hidden there!
n
Trust the error message.
Another very common beginner’s mis-
take is to not fully read or trust the error
that PHP reports. Although an error
message can often be cryptic and may
seem meaningless, it can’t be ignored.
At the very least, PHP is normally cor-
rect as to the line on which the problem
can be found. And if you need to relay
that error message to someone else
[like when you’re asking me for help],
do include the entire error message!
n
Take a break!
So many of the programming problems
I’ve encountered over the years, and
the vast majority of the toughest ones,
have been solved by stepping away
from my computer for a while. It’s easy
to become frustrated and confused,
and in such situations, any further steps
you take are likely to make matters
only worse.
These are just some general debugging
techniques, specifically tailored to the begin-
ning PHP programmer. They should suffice
for now, because the examples in this book
are relatively simple. More complex coding
requires more advanced debugging tech-
niques, so my PHP and MySQL for Dynamic
Web Sites: Visual QuickPro Guide, Fourth
Edition [Peachpit Press, 2012] dedicates a
whole chapter to this subject.
ptg18144795
Getting Started with PHP 29
Review and Pursue
Each chapter in this book ends with a
“Review and Pursue” section. In these
sections you’ll find:
n
Questions regarding the material just
covered
n
Prompts for ways to expand your
knowledge and experience on your own
If you have any problems with these
sections, in either answering the questions
or pursuing your own endeavors, turn
to the book’s supporting forum
[www.LarryUllman.com/forums/].
Review
n
What is HTML? What is the current
version of HTML?
n
What encoding is your text editor or IDE
set to use? Does that match the encod-
ing specified in your generated HTML
pages? Why does the encoding matter?
n
What is CSS and what is it used for?
n
What file extension should PHP scripts
have for your particular server?
n
What is meant by “web root directory”?
What is the web root directory for
your server?
n
How do you test PHP scripts? What
happens when PHP scripts are not
run through a URL?
n
Name two ways comments can be
added to PHP code. Identify some
reasons to use comments.
ptg18144795
30 Chapter 1
Pursue
n
If you have access to more than one
server, confirm what version of PHP is
running on another server.
n
Create a static HTML page that displays
some information. Then replace some of
the static content with content created
by PHP.
n
Create a template to use for your own
work. The template should contain the
HTML shell, the opening and closing
PHP tags, and some basic comments.
n
Confirm, using the
phpinfo[]
function,
that
display_errors
is enabled on
your server. If it’s not, change your
server’s configuration to enable it [see
Chapter 3 and Appendix A].
n
In subsequent chapters, occasionally
check the PHP manual’s page when a
new function is mentioned in the book.
ptg18144795
The previous chapter covered how to use
PHP to send simple text and HTML to a
web browser—in other words, something
for which you don’t need PHP at all! Don’t
worry, though; this book will teach you how
to use
in conjunction with other PHP
features to do great and useful things with
your website.
To make the leap from creating simple,
static pages to dynamic web applications
and interactive websites, you need vari-
ables. Understanding what variables are,
the types of variables that a language sup-
ports, and how to use them is critical.
This chapter introduces the fundamentals
of variables in PHP, and later chapters
cover the different types in greater detail.
If you’ve never dealt with variables before,
this chapter will be a good introduction. If
you’re familiar with the concept, then you
should be able to work through this chapter
with ease.
2
Variables
In This Chapter
What Are Variables? 32
Variable Syntax 36
Types of Variables 38
Variable Values 41
Understanding Quotation Marks 44
Review and Pursue 48
ptg18144795
32 Chapter 2
What Are Variables?
A
variable
is a container for data. Once
data has been stored in a variable [or,
stated more commonly, once a variable
has been assigned a value], that data can
be altered, printed to the browser, saved to
a database, emailed, and so forth.
Variables in PHP are, by their nature,
flexible: You can put data into a variable,
retrieve that data from it [without affecting
the value of the variable], put new data in
it, and continue this cycle as many times
as necessary. But variables in PHP are
largely temporary:
Most only exist
—that is,
they only have a value—
for the duration
of the script’s execution on the server
.
Once the execution of the script completes
[often when the final closing PHP tag is
encountered], those variables cease to
exist. Furthermore, after users click a link
or submit a form, they are taken to a new
page that may have an entirely separate
set of variables.
Before getting too deep into the discus-
sion of variables, let’s write a quick script
that reveals some of PHP’s
predefined
variables. These are variables that PHP
automatically creates when a script runs.
Over the course of the book, you’ll be
introduced to many different predefined
variables. This particular example looks
at the predefined
$_SERVER
variable. It
contains lots of information about the com-
puter on which PHP is running.
The
print_r[]
function offers an easy way
to display any variable’s value:
print_r[$variable_name];
Just provide the name of the variable
you’d like to inspect as a single argument
to the
print_r[]
function. [You’ll learn
more about a variable’s syntax throughout
this chapter.]
ptg18144795
Variables 33
To print PHP’s predefined variables:
1. Create a new PHP script in your
text editor or IDE, to be named
predefined.php
[Script 2.1].
2. Create the initial HTML tags:
Predefined Variables
➝
This code repeats the HTML template
created in the preceding chapter. Within
the body of the page, the
tags
are being used to make the generated
PHP information more legible. Without
using the
tags, the
print_r[]
function’s output would be difficult to
read in a browser.
3. Add the PHP code:
The PHP code contains just one func-
tion call. The function should be pro-
vided with the name of a variable.
In this example, the variable is
$_SERVER
, which is special in PHP.
$_SERVER
stores all sorts of data about
the server: its name and operating
system, the name of the current user,
information about the web server appli-
cation [Apache, Nginx, IIS, and so on],
and more. It also reflects the PHP script
being executed: its name, where it’s
stored on the server, and so forth.
continues on next page
Script 2.1 This script uses the
print_r[]
function
to show the values stored in the
$_SERVER
predefined variable.
1
2
3
4
5 Predefined Variables
6
7
8
9
15
16
17
ptg18144795
34 Chapter 2
Note that you must type
$_SERVER
exactly as it is here, in all upper-
case letters.
4. Complete the HTML page:
5. Save the file as
predefined.php
,
upload it to your server [or save it to the
appropriate directory on your com-
puter], and test it in your browser A.
Once again, remember that you must
run all PHP scripts through a URL [that
is, //
something
].
6. If possible, transfer the file to another
computer or server running PHP and
execute the script in your browser
again B.
Printing out the value of any variable
as you’ve done here is one of the greatest
debugging tools. Scripts often don’t work
as you expect them to because one or more
variables do not have the values you assume
they should, so confirming their actual values
is extremely helpful.
If you don’t use the HTML
tags, the result will be like the jumble of infor-
mation in C.
A The
$_SERVER
variable, as printed out by this script, is a master list
of values pertaining to the server and the PHP script.
ptg18144795
Variables 35
B With the
predefined.php
page, different servers will generate different
results [compare with A].
C With large, complex variables such as
$_SERVER
, not using the HTML
preformatting tags with
print_r[]
creates an incomprehensible mess
[compare to A B].
ptg18144795
36 Chapter 2
Variable Syntax
Now that you’ve had a quick dip in the vari-
able pool, it’s time to swim a bit deeper. In
the preceding example, the script printed
out the value of PHP’s predefined
$_SERVER
variable. You can also create your own
variables, once you understand the proper
syntax. To create appropriate variable
names, you must follow these rules:
n
All variable names must be preceded
by a dollar sign [
$
].
n
Following the dollar sign, the variable
name must begin with either a letter
[A–Z, a–z] or an underscore [
_
]. A num-
ber cannot immediately follow the
dollar sign.
n
The rest of the variable name can con-
tain any combination of letters, under-
scores, and numbers.
n
You may not use spaces within the
name of a variable. [Instead, the under-
score is commonly used to separate
words.]
n
Each variable must have a unique
name.
n
Variable names are
case-sensitive
!
Consequently,
$variable
and
$Variable
are two different constructs,
and it would be a bad idea to use two
variables with such similar names.
This last point is perhaps the most important:
Variable names in PHP are case-sensitive.
Using the wrong letter case is a very
common cause of bugs. [If you used, for
example,
$_server
or
$_Server
in the
previous script, you’d see either an error
message or nothing at all A.]
A Misspelling a variable’s name, including its
case, will create undesired and unpredictable
results.
ptg18144795
Variables 37
To help minimize bugs, I recommend the
following policies:
n
Always use all lowercase variable names.
n
Make your variable names descriptive
[for example,
$first_name
is better
than
$fn
].
n
Use comments to indicate the purpose
of variables [Script 2.2], redundant as
that may seem.
n
Above all, be consistent with whatever
naming convention you choose!
Table 2.1 lists some sample valid variables;
Table 2.2 lists some invalid variables and
the rules they violate.
Unlike some other languages, PHP
doesn’t require you to declare or initialize a
variable prior to use, although PHP does issue
warnings when you do. In other words, you
can refer to variables without first defining
them. But it’s best not to do that; try to write
scripts so that every variable is defined or
validated before use.
There are two main variable naming
conventions, determined by how you delineate
words. These are the so-called camel-hump
or camel-case [named because of the way
capital letters break up the word—for example,
$FirstName
] and underscore [
$first_name
]
styles. This book uses the latter convention.
Script 2.2 Properly documenting the purposes of
variables, along with using meaningful names, is a
hallmark of a professional programmer.
1
2
3
4
5 Variables and Comments
6
7
8
17
18
TABLE 2.1 Valid Variables in PHP
Name
$first_name
$person
$address1
$_SERVER
TABLE 2.2 Invalid Variables in PHP
Name Reason
$first name
Has a space
$first.name
Has a period
first_name
Does not begin with
$
$1address
A number cannot follow
$
ptg18144795
38 Chapter 2
Types of Variables
This book covers three common PHP vari-
able types:
numbers
,
strings
, and
arrays
.
This chapter introduces them quickly, and
later chapters discuss them in more detail:
n
Chapter 4, “Using Numbers”
n
Chapter 5, “Using Strings”
n
Chapter 7, “Using Arrays”
A fourth variable type,
objects
, is intro-
duced in Appendix B, “Resources and Next
Steps,” but isn’t covered in this book. That
particular subject is just too advanced for
a beginner’s guide—in fact, basic coverage
of the subject in my
PHP Advanced and
Object-Oriented Programing: Visual
QuickPro Guide, Third Edition
[Peachpit
Press, 2013] requires over 150 pages!
TABLE 2.3 Valid Numbers in PHP
Number Type
1 Integer
1.0 Floating-point
1972 Integer
19.72 Floating-point
–1 Integer
–1.0 Floating-point
TABLE 2.4 Invalid Numbers in PHP
Number Reason
1/3Contains a slash
1996aContains a letter
08.02.06 Contains multiple
decimals
Numbers
Technically speaking, PHP breaks numbers
into two types:
integers
and
floating-point
[also known as
double-precision
floating-
point
or
doubles
]. Due to the lax way PHP
handles variables, it largely won’t affect your
programming to group the two categories
of numbers into one all-inclusive member-
ship, at least when you’re just starting out.
Still, let’s briefly discuss the differences
between the two, to be precise.
The first type of numbers—
integers
—is also
known as
whole numbers
. They can be pos-
itive or negative but include neither fractions
nor decimals. Numbers that use a decimal
point [even something like 1.0] are
floating-
point
numbers, also known as
floats
. You
use floating-point numbers to refer to frac-
tions, because the only way to express a
fraction in PHP is to convert it to its decimal
equivalent. Hence, 1¼ is written as 1.25.
Table 2.3 lists some sample valid numbers
and their formal type; Table 2.4 lists invalid
numbers and the rules they violate.
As you’ll soon see, you add quotation
marks around invalid numbers to turn them
into valid strings.
ptg18144795
Variables 39
Strings
A string is any number of characters
enclosed within a pair of either single [
'
]
or double [
"
] quotation marks. Strings can
contain any combination of characters
that exist: letters, numbers, symbols, and
spaces. Strings can also contain variables.
Here are examples of valid string values:
"Hello, world!"
"Hello, $first_name!"
"1/3"
'Hello, world! How are you today?'
"08.02.06"
"1996"
''
That last example is an
empty string
—a
string that contains no characters.
To create a string, just wrap 0 or more
characters within quotation marks. There
are cases, however, where you may run
into problems. For example:
"I said, "How are you?""
This string will be tricky. Chapter 1, “Getting
Started with PHP,” hinted at the same prob-
lem with respect to printing HTML code.
When PHP hits the second quotation mark
in the example, it assumes the string ends
there; the continuing text [
How…
] causes
an error. To use a quotation mark within a
string you
escape
the quotation mark by
putting a backslash [
\
] before it:
"I said, \"How are you?\""
The backslash tells PHP to treat each
escaped quotation mark as part of the
value
of the string, rather than using it as
the string’s opening or closing indicators.
You can similarly circumvent this problem
by using different quotation mark types:
'I said, "How are you?"'
"I said, 'How are you?'"
Notice that “1996” converts an integer
into a string, simply by placing the number
within quotes. Essentially, the string contains
the characters 1996, whereas the number [a
nonquoted value] would be equal to 1996. It’s
a fine distinction, and one that won’t matter
in your code, because PHP lets you perform
mathematical calculations with the string 1996
just as you can with the number.
Chapter 1 also demonstrated how to
create a new line by printing the
\n
charac-
ter within double quotation marks. Although
escaping a quotation mark prints the quota-
tion mark, escaping an n prints a new line,
escaping an r creates a carriage return, and
escaping a t creates a tab.
Understanding strings, variables, and the
single and double quotation marks is critical
to programming with PHP. For this reason, a
section at the end of this chapter is dedicated
to the subject.
ptg18144795
40 Chapter 2
Arrays
Arrays are covered more thoroughly in
Chapter 7, but let’s look at them briefly
here. Whereas a string or a number con-
tains a single value [both are said to be
scalar
], an array can have more than one
value assigned to it. You can think of an
array as a list or table of values: You can
put multiple strings and/or numbers into
one array.
Arrays use
keys
to create and retrieve the
values they store. The resulting structure—
a list of key-value pairs—is similar to a
two-column spreadsheet. Unlike arrays in
other programming languages, the array
structure in PHP is so flexible that it can use
either numbers or strings for both the keys
and the values. The array doesn’t even need
to be consistent in this respect. [All of this
will make more sense in Chapter 7, when
you start working with specific examples.]
PHP supports two kinds of arrays, based
on the format of the keys. If the array uses
numbers for the keys [Table 2.5], it’s known
as an
indexed
array. If it uses strings for
the keys [Table 2.6], it’s an
associative
array. In either case, the values in the array
can be of any variable type [string, number,
and so on].
The array’s key is also referred to as
its index. You’ll see these two terms used
interchangeably.
An array can, and frequently will, contain
other arrays, creating what is called a multi-
dimensional array.
What PHP refers to as an associative
array is known as a hash in Perl and Ruby,
among other languages.
TABLE 2.5 Indexed Array
Key Value
0 Dev
1 Rachel
2 Denise
3 Arnold
TABLE 2.6 Associative Array
Key Value
VT Vermont
NHNew Hampshire
IA Iowa
PA Pennsylvania
ptg18144795
Variables 41
Variable Values
To assign a value to a variable, regardless
of the variable type, you use the equals
sign [
=
]. Therefore, the equals sign is known
as the
assignment operator
, because it
assigns the value on the right to the variable
on the left. For example:
$number = 1;
$floating_number = 1.2;
$string = "Hello, world!";
Each of these lines represents a complete
statement [that is, an executable action],
so each concludes with a semicolon.
To print the value of a variable, use the
function:
print $number;
print $string;
If you want to print a variable’s value within
a context, you can place the variable’s
name in the printed string, as long as you
use double quotation marks A:
print "Number is $number";
print "String is $string";
Using
in this way works for the sca-
lar [single-valued] variable types—numbers
and strings. For complex variable types—
arrays and objects—you cannot just use
B:
print "_SERVER is $_SERVER";
As you’ve already seen,
print_r[]
can
handle these nonscalar types, and you’ll
learn other approaches later in the book.
Whether you’re dealing with scalar or non-
scalar variables, don’t forget that printing
out their values is an excellent debugging
technique when you’re having problems
with a script.
A The result of printing the values
of two variables.
B Using the
statement on a complex
variable type, such as an array, will not have the
results you desire.
ptg18144795
42 Chapter 2
Because variable types aren’t locked in
[PHP is referred to as a
weakly typed
lan-
guage], they can be changed on the fly:
$variable = 1;
$variable = "Greetings";
If you were to print the value of
$variable
now, the result would be
Greetings
. The
following section better demonstrates the
concept of assigning values to variables
and then accessing those values.
To assign values to and
access variables:
1. Create a new PHP script in your
text editor or IDE, to be named
variables.php
[Script 2.3].
2. Create the initial HTML tags:
Variables
3. Begin the PHP code:
20
21
ptg18144795
Variables 43
Remember that each statement must
conclude with a semicolon and that the
variable names are case-sensitive.
5. Print out the values of the variables
within some context:
print "
The address is:
➝
$street
$city $state➝
$zip
";Here a single
statement refer-
ences all the variables. The entire string
to be printed [consisting of text, HTML
tags, and variables] is enclosed within
double quotation marks. The HTML
tags make the text flow over mul-
tiple lines in the browser.
6. Complete the PHP section and the
HTML page:
?>
7. Save the file as
variables.php
, upload
it to your server [or save it to the appro-
priate directory on your computer], and
test it in your browser C.
If you see a parse error D when you
run this script, you probably either omitted
a semicolon or have an imbalance in your
quotation marks. In such particular cases, the
mistake itself is likely on the previous line of
code [than reported in the error message] but
wasn’t caught by PHP until the next line.
If one of the variable’s values isn’t
printed out or you see an Undefined variable
error E, you most likely failed to spell a
variable name the same way twice.
If you see a blank page, you most likely
have an error but PHP’s
display_errors
configuration is set to off. See Chapter 3,
“HTML Forms and PHP,” for details.
C Some variables are assigned values, and then
printed within a context.
D Parse errors are the most common type of PHP
error, as you’ll discover. They’re frequently caused
by missing semicolons or mismatched quotation
marks or parentheses.
E The
Undefined variable
error indicates that
you used a variable with no value [it hasn’t been
defined]. This can happen with misspellings and
capitalization inconsistencies.
ptg18144795
44 Chapter 2
Understanding
Quotation Marks
Now that you know the basics of variables
and how to create them, let’s do an exer-
cise to make sure you completely under-
stand how to properly use quotation marks.
PHP, like most programming languages,
allows you to use both double [
"
] and
single [
'
] quotation marks—but they give
vastly different results. It’s critical that you
comprehend the distinction, so the next
example will run tests using both types just
to emphasize the different behaviors.
The rule to remember is:
Items within
single quotation marks are treated literally;
items within double quotation marks
are extrapolated
. This means that within
double quotation marks, a variable’s name
is replaced with its value, as in Script 2.3,
but the same is not true for single quota-
tion marks.
This rule applies anywhere in PHP you
might use quotation marks, including
uses of the
function and the assign-
ment of values to string variables. An
example is the best way to demonstrate
this critical concept.
ptg18144795
Variables 45
To use quotation marks:
1. Begin a new PHP script in your text
editor or IDE, to be named
quotes.php
[Script 2.4].
2. Create the initial HTML tags:
Quotes
3. Begin the PHP code: