PHP can work with different types of data. In this chapter, you’ll learn about individual values such as numbers and single pieces of text. You’ll learn how to put text and numbers in your programs, as well as some of the limitations the PHP engine puts on those values and some common tricks for manipulating them.
Most PHP programs spend a lot of time handling text because they spend a lot of time generating HTML and working with information in a database. HTML is just a specially formatted kind of text; and information in a database, such as a username, a product description, or an address, is a piece of text, too. Slicing and dicing text easily means you can build dynamic web pages easily.
In Chapter 1, you saw variables in action, but this chapter teaches you more about them. A variable is a named container that holds a value. The value that a variable holds can change as a program runs. When you access data submitted from a form or exchange data with a database, you use variables. In real life, a variable is something such as your checking account balance. As time goes on, the value that the phrase “checking account balance” refers to fluctuates. In a PHP program, a variable might hold the value of a submitted form parameter. Each time the program runs, the value of the submitted form parameter can be different. But whatever the value, you can always refer to it by the same name. This chapter also explains in more detail what variables are: how you create them and do things such as change their values or print them.
When they’re used in computer programs, pieces of text are called
strings. This is because they consist of individual
items, strung together. Strings can contain letters, numbers,
punctuation, spaces, tabs, or any other characters. Some examples of
strings are
I would like 1 bowl of soup, and "Is it too hot?"
he asked, and There's no spoon!. A string can even
contain the contents of a binary file, such as an image or a sound. The
only limit to the length of a string in a PHP program is the amount of
memory your computer has.
Strings in PHP are sequences of bytes, not characters. If you’re dealing only with English text then this distinction won’t affect you. If you work with non-English text and need to make sure that your characters in other alphabets are handled properly, make sure to read Chapter 20, which discusses working with different character sets.
There are a few ways to indicate a string in a PHP program. The simplest is to surround the string with single quotes:
'I would like a bowl of soup.';'chicken';'06520';'"I am eating dinner," he growled.';
Since the string consists of everything inside the single quotes, that’s what is printed:
I would like a bowl of soup.chicken06520"I am eating dinner," he growled.
Note that the output of those four print statements appears
all on one line. No line breaks are added by
print.1
The single quotes aren’t part of the string. They
are delimiters, which tell the PHP engine
where the start and end of the string is. If you want to include a
single quote inside a string surrounded with single quotes, put a
backslash (\)
before the single quote inside the string:
'We\'ll each have a bowl of soup.';
The \' sequence is turned into ' inside the string, so
what is printed is:
We'll each have a bowl of soup.
The backslash tells the PHP engine to treat the following character as a literal single quote instead of the single quote that means “end of string.” This is called escaping, and the backslash is called the escape character. An escape character tells the system to do something special with the character that comes after it. Inside a single-quoted string, a single quote usually means “end of string.” Preceding the single quote with a backslash changes its meaning to a literal single quote character.
The escape character can itself be escaped. To include a literal backslash character in a string, put a backslash before it:
'Use a \\ to escape in a string';
This prints:
Use a \ to escape in a string
The first backslash is the escape character: it tells the PHP engine that something different is going on with the next character. This affects the second backslash: instead of the special action (“treat the next character literally”), a literal backslash is included in the string.
Note that these are backslashes that go from top left to bottom
right, not forward slshes that go from bottom left to top right.
Remember that two forward slashes in a PHP program (//) indicate a
comment.
You can include whitespace such as newlines in single-quoted strings:
'<ul><li>Beef Chow-Fun</li><li>Sauteed Pea Shoots</li><li>Soy Sauce Noodles</li></ul>';
This puts the HTML on multiple lines:
<ul><li>Beef Chow-Fun</li><li>Sauteed Pea Shoots</li><li>Soy Sauce Noodles</li></ul>
Since the single quote that marks the end of the string is
immediately after the </ul>, there is no
newline at the end of the string.
The only characters that get special treatment inside single-quoted strings are the backslash and single quote. Everything else is treated literally.
You can also delimit strings with double quotes. Double-quoted strings are similar to single-quoted strings, but they have more special characters. These special characters are listed in Table 2-1.
| Character | Meaning |
|---|---|
\n | Newline (ASCII 10) |
\r | Carriage return (ASCII 13) |
\t | Tab (ASCII 9) |
\\ | \ |
\$ | $ |
\" | " |
\0 .. \777 | Octal (base 8) number |
\x0 .. \xFF | Hexadecimal (base 16) number |
The biggest difference between single-quoted and double-quoted
strings is that when you include variable names inside a double-quoted
string, the value of the variable is substituted into the string,
which doesn’t happen with single-quoted strings. For example, if the
variable $user holds the value Bill, then
'Hi $user' is just that: Hi $user.
However, "Hi $user" is Hi Bill. “Variables” gets into this in more detail.
As mentioned in “PHP in Action”, you can also define
strings with the here document syntax. A here document begins
with
<<< and a delimiter word. It ends
with the same word at the beginning of a line. Example 2-1 shows a here document.
<<<HTMLBLOCK <html> <head><title>Menu</title></head> <body bgcolor="#fffed9"> <h1>Dinner</h1> <ul> <li> Beef Chow-Fun <li> Sauteed Pea Shoots <li> Soy Sauce Noodles </ul> </body> </html> HTMLBLOCK
In Example 2-1, the delimiter word is
HTMLBLOCK. Here document delimiters can contain letters,
numbers, and the underscore character. The first character of the
delimiter must be a letter or underscore. It’s a good idea to
make all the letters in your here document delimiters uppercase to
visually set off the here document. The delimiter that ends the here
document must be alone on its line. The delimiter can’t be indented
and no whitespace, comments, or other characters are allowed after
it. The only exception to this is that a semicolon is allowed
immediately after the delimiter to end a statement. In that case,
nothing can be on the same line after the semicolon. The code
in Example 2-2
follows these rules to print a here document.
<<<HTMLBLOCK<html><head><title>Menu</title></head><body bgcolor="#fffed9"><h1>Dinner</h1><ul><li> Beef Chow-Fun<li> Sauteed Pea Shoots<li> Soy Sauce Noodles</ul></body></html>HTMLBLOCK;
Here documents obey the same escape character and variable substitution rules as double-quoted strings. This makes them especially useful when you want to define or print a string that contains a lot of text or HTML with some variables mixed in. Later on in the chapter, Example 2-22 demonstrates this.
To combine two strings, use a . (period), the string
concatenation operator. Here are some combined strings:
'bread'.'fruit';"It's a beautiful day ".'in the neighborhood.';"The price is: ".'$3.95';'Inky'.'Pinky'.'Blinky'.'Clyde';
The combined strings print as:
breadfruit It's a beautiful day in the neighborhood. The price is: $3.95 InkyPinkyBlinkyClyde
PHP has a number of built-in functions that are useful when working with strings. This section introduces the functions that are most helpful for two common tasks: validation and formatting. The “Strings” chapter of the online PHP Manual has information on other built-in string handling functions.
Validation is the process of checking that input coming from an external source conforms to an expected format or meaning. It’s making sure that a user really entered a zip code in the “zip Code” box of a form or a reasonable email address in the appropriate place. Chapter 7 delves into all the aspects of form handling, but since submitted form data is provided to your PHP programs as strings, this section discusses how to validate those strings.
The trim() function removes whitespace from the
beginning and end of a string. Combined with strlen(),
which tells you the length of a string, you can use this function to find out the length of
a submitted value while ignoring any leading or trailing
spaces. Example 2-3 shows you how. (Chapter 3 discusses in more detail
the if() statement used in Example 2-3.)
// $_POST['zipcode'] holds the value of the submitted form parameter// "zipcode"$zipcode=trim($_POST['zipcode']);// Now $zipcode holds that value, with any leading or trailing spaces// removed$zip_length=strlen($zipcode);// Complain if the zip code is not 5 characters longif($zip_length!=5){"Please enter a zip code that is 5 characters long.";}
Using trim() protects against someone who types a
zip code of 732 followed by two spaces. Sometimes
the extra spaces are accidental, and sometimes they are malicious.
Whatever the reason, throw them away when appropriate to make sure
that you’re getting the string length you care
about.
You can chain together the calls to trim() and
strlen() for more concise code. Example 2-4 does the same thing as Example 2-3.
if(strlen(trim($_POST['zipcode']))!=5){"Please enter a zip code that is 5 characters long.";}
Four things happen in the first line of Example 2-4.
First, the value of the variable $_POST['zipcode']
is passed to the trim() function. Second, the
return value of that function—$_POST['zipcode'] with leading and trailing
whitespace removed—is handed off to the strlen() function, which then returns the length of the trimmed
string. Third, this length is compared with 5. Last, if the length is
not equal to 5 the print statement inside
the if() block runs.
To compare two strings, use the equal operator (==), as shown in Example 2-5.
if($_POST['email']=='president@whitehouse.gov'){"Welcome, US President.";}
The print statement in Example 2-5 runs only if the submitted form parameter
email is the all-lowercase
president@whitehouse.gov. When comparing strings
with ==, case is important. The string president@whitehouse.GOV is not the same as
President@Whitehouse.Gov or
president@whitehouse.gov.
To compare strings without paying attention to case,
use strcasecmp(). It compares two strings while
ignoring differences in capitalization. If the two strings you
provide to strcasecmp() are the same independent of any
differences between upper- and lowercase letters, it returns
0. Example 2-6
shows how to use strcasecmp().
if(strcasecmp($_POST['email'],'president@whitehouse.gov')==0){"Welcome back, US President.";}
The print statement in Example 2-6 runs if the submitted form parameter email is President@Whitehouse.Gov, PRESIDENT@WHITEHOUSE.GOV, presIDENT@whiteHOUSE.GoV, or any other capitalization of president@whitehouse.gov.
The printf() function gives you more control
(compared to print) over how the output looks. You
pass printf() a format string and a bunch of items to
print. Each rule in the format string is replaced by one
item. Example 2-7
shows printf() in action.
$price=5;$tax=0.075;printf('The dish costs $%.2f',$price*(1+$tax));
This prints:
The dish costs $5.38
In Example 2-7, the format rule
%.2f is replaced with the value of $price
* (1 + $tax) and formatted so that it
has two decimal places.
Format string rules begin with % and then have some
optional modifiers that affect what the rule does:
0
to pad with zeros.
+) makes printf() put a + before positive numbers (normally,
they’re printed without a sign.) For strings, a
minus sign (-) makes
printf() right-justify the string (normally,
they’re left-justified.)
.2 formats $price * (1
+ $tax) with two decimal places.
After the modifiers come a mandatory character that indicates what
kind of value should be printed. The three discussed here are
d for decimal number, s for
string, and f for floating-point number.
If this stew of percent signs and modifiers has you scratching your
head, don’t worry. The most frequent use of
printf() is probably to format prices with the
%.2f format rule as shown in Example 2-7. If you absorb nothing else about
printf() for now, just remember that
it’s your go-to function when you want to format a
decimal value.
But if you delve a little deeper, you can do some other handy things
with it. For example, using the 0 padding
character and a minimum width, you can format a date or zip code
properly with leading zeros, as shown in Example 2-8.
$zip='6520';$month=2;$day=6;$year=2007;printf("ZIP is %05d and the date is %02d/%02d/%d",$zip,$month,$day,$year);
Example 2-8 prints:
ZIP is 06520 and the date is 02/06/2007
The sign modifier is helpful for explicitly indicating positive and negative values. Example 2-9 uses it to display some temperatures.
$min=-40;$max=40;printf("The computer can operate between %+d and %+d degrees Celsius.",$min,$max);
Example 2-9 prints:
The computer can operate between -40 and +40 degrees Celsius.
To learn about other printf() format rules, visit
http://www.php.net/sprintf.
Another kind of text formatting is to manipulate the case of
strings. The functions strtolower() and
strtoupper() make all-lowercase and
all-uppercase versions, respectively, of a string. Example 2-10 shows strtolower() and strtoupper() at work.
strtolower('Beef, CHICKEN, Pork, duCK');strtoupper('Beef, CHICKEN, Pork, duCK');
Example 2-10 prints:
beef, chicken, pork, duck BEEF, CHICKEN, PORK, DUCK
The ucwords() function uppercases the first letter of
each word in a string. This is useful when combined
with strtolower() to produce nicely capitalized names
when they are provided to you in all uppercase. Example 2-11 shows how to
combine strtolower() and ucwords().
ucwords(strtolower('JOHN FRANKENHEIMER'));
Example 2-11 prints:
John Frankenheimer
With the
substr()
function, you can extract just part of a string. For example, you may
only want to display the beginnings of messages on a summary page. Example 2-12 shows how to use substr()
to truncate the submitted form parameter comments.
// Grab the first 30 bytes of $_POST['comments']substr($_POST['comments'],0,30);// Add an ellipsis'...';
If the submitted form parameter comments is:
The Fresh Fish with Rice Noodle was delicious, but I didn't like the Beef Tripe.
Example 2-12 prints:
The Fresh Fish with Rice Noodl...
The three arguments to substr() are the string to
work with, the starting position of the substring to extract, and the
number of bytes to extract. The beginning of the string is
position 0, not 1, so substr($_POST['comments'], 0,
30) means “extract 30 bytes from
$_POST['comments'] starting at the beginning of
the string.”
When you give substr() a negative number for a
start position, it counts back from the end of the string to figure
out where to start. A start position of -4 means
“start four bytes from the
end.” Example 2-13 uses a negative
start position to display just the last four digits of a credit card
number.
'Card: XX';substr($_POST['card'],-4,4);
If the submitted form parameter card is
4000-1234-5678-9101, Example 2-13
prints:
Card: XX9101
As a shortcut, use substr($_POST['card'],-4)
instead of substr($_POST['card'], -4,4). When you
leave out the last argument, substr() returns
everything from the starting position (whether positive or negative)
to the end of the string.
Instead of extracting a substring, the str_replace()
function changes parts of a string. It looks for a substring and
replaces the substring with a new string. This is useful for simple
template-based customization of HTML. Example 2-14
uses str_replace() to set the
class attribute of <span>
tags.
$html='<span class="{class}">Fried Bean Curd<span><span class="{class}">Oil-Soaked Fish</span>';str_replace('{class}',$my_class,$html);
If $my_class has been set to lunch, then
Example 2-14 prints:
<span class="lunch">Fried Bean Curd<span> <span class="lunch">Oil-Soaked Fish</span>
Each instance of {class} (the first argument to
str_replace()) is replaced by
lunch (the value of $my_class)
in the string that is the third argument passed to
str_replace().
Numbers in PHP are expressed using familiar notation, although you can’t use commas or any other characters to group thousands. You don’t have to do anything special to use a number with a decimal part as compared to an integer. Example 2-15 prints some valid numbers in PHP.
56;56.3;56.30;0.774422;16777.216;0;-213;1298317;-9912111;-12.52222;0.00;
Internally, the PHP engine makes a distinction between numbers with a decimal part and those without one. The former are called floating-point numbers and the latter are called integers. Floating-point numbers take their name from the fact that the decimal point can “float” around to represent different amounts of precision.
The PHP engine uses the math facilities of your operating system to represent numbers, so the largest and smallest numbers you can use, as well as the number of decimal places you can have in a floating-point number, vary on different systems.
One distinction between the PHP engine’s internal representation of integers and floating-point numbers is the exactness of how they’re stored. The integer 47 is stored as exactly 47. The floating-point number 46.3 could be stored as 46.2999999. This affects the correct technique of how to compare numbers. “Building Complicated Decisions” explains comparisons and shows how to properly compare floating-point numbers.
Doing math in PHP is a lot like doing math in elementary school, except it’s much faster. Some basic operations between numbers are shown in Example 2-16.
2+2;17-3.5;10/3;6*9;
The output of Example 2-16 is:
4 13.5 3.3333333333333 54
In addition to the plus sign (+) for
addition, the minus sign (-) for subtraction, the forward
slash (/) for division, and the asterisk (*)
for multiplication, PHP also supports two asterisks (**) for exponentiation and the percent sign (%) for modulus division (returning the remainder of a division operation):
17%3;
This prints:
2
Since 17 divided by 3 is 5 with a remainder of 2, 17 % 3 equals 2. The modulus operator is useful for printing rows whose CSS class names alternate in an HTML table, as shown in Example 4-13.
The exponentiation operator was introduced in PHP 5.6. If you’re using an older version of PHP, use the pow() function.
The arithmetic operators, as well as the other PHP operators that you’ll meet later in the book, fit into a strict precedence of operations. This is how the PHP engine decides in what order to do calculations if they are written ambiguously. For example, “3 + 4 * 2” could mean “add 3 and 4 and then multiply the result by 2,” which results in 14. Or, it could mean “add 3 to the product of 4 and 2,” which results in 11. In PHP (as well as the math world in general), multiplication has a higher precedence than addition, so the second interpretation is correct. First, the PHP engine multiplies 4 and 2, and then it adds 3 to the result.
The precedence table of all PHP operators is part of the online PHP Manual. You can avoid the need to memorize or repeatedly refer to this table, however, with a healthy dose of parentheses. Grouping operations inside parentheses unambiguously tells the PHP engine to do what’s inside the parentheses first. The expression “(3 + 4) * 2” means “add 3 and 4 and then multiply the result by 2.” The expression “3 + (4 * 2)” means “multiply 4 and 2 and then add 3 to the result.”
Like in other modern programming languages, you don’t have to do anything special to ensure that the results of your calculations are properly represented as integers or floating-point numbers. Dividing one integer by another produces a floating-point result if the two integers don’t divide evenly. Similarly, if you do something to an integer that makes it larger than the maximum allowable integer or smaller than the minimum possible integer, the PHP engine converts the result into a floating-point number so you get the proper result for your calculation.
Variables hold the data that your program manipulates while it
runs, such as user information that you’ve loaded from a
database or entries that have been typed into an HTML form. In PHP,
variables are denoted by a $ followed by the variable’s name. To assign a value to a variable, use an equals sign (=). This
is known as the assignment operator.
Here are a few examples:
$plates=5;$dinner='Beef Chow-Fun';$cost_of_dinner=8.95;$cost_of_lunch=$cost_of_dinner;
Assignment works with here documents as well:
$page_header=<<<HTML_HEADER<html><head><title>Menu</title></head><body bgcolor="#fffed9"><h1>Dinner</h1>HTML_HEADER;$page_footer=<<<HTML_FOOTER</body></html>HTML_FOOTER;
Variable names may only include:
A-Z and a-z)0-9)_)ç or
or
), if you’re using a character encoding such as UTF-8 for your program fileAdditionally, the first character of a variable name is not allowed to be a digit. Table 2-2 lists some allowable variable names.
$size |
$drinkSize |
$SUPER_BIG_DRINK |
$_d_r_i_n_k_y |
$drink4you2 |
$напиток |
$သောက်စရာ |
$🄳🅁🄸🄽🄺 |
$😀 |
Keep in mind that, despite the alluring aesthetic possibilities of variable names with emoticons in them, most PHP code sticks with digits, underscores, and Basic Latin letters.
Table 2-3 lists some disallowed variable names and what’s wrong with them.
| Variable name | Flaw |
|---|---|
$2hot4u |
Begins with a number |
$drink-size |
Unacceptable character: - |
$drinkmaster@example.com |
Unacceptable characters: @ and . |
$drink!lots |
Unacceptable character: ! |
$drink+dinner |
Unacceptable character: + |
Variable names are case-sensitive. This means that
variables named $dinner,
$Dinner, and $DINNER are
separate and distinct, with no more in common than if they were named
$breakfast, $lunch, and
$supper. In practice, you should avoid using
variable names that differ only by letter case. They make programs
difficult to read and debug.
Arithmetic and string operators work on variables containing numbers or strings just like they do on literal numbers or strings. Example 2-17 shows some math and string operations at work on variables.
$price=3.95;$tax_rate=0.08;$tax_amount=$price*$tax_rate;$total_cost=$price+$tax_amount;$username='james';$domain='@example.com';$email_address=$username.$domain;'The tax is '.$tax_amount;"\n";// this prints a line break'The total cost is '.$total_cost;"\n";// this prints a line break$email_address;
Example 2-17 prints:
The tax is 0.316 The total cost is 4.266 james@example.com
The assignment operator can be combined
with arithmetic and string operators for a concise way to modify a
value. An operator followed by the equals sign means
“apply this operator to the
variable.” Example 2-18 shows two
identical ways to add 3 to $price.
// Add 3the regular way$price=$price+3;// Add 3 with the combined operator$price+=3;
Combining the assignment operator with the string concatenation operator appends a value to a string. Example 2-19 shows two identical ways to add a suffix to a string. The advantage of the combined operators is that they are more concise.
$username='james';$domain='@example.com';// Concatenate $domain to the end of $username the regular way$username=$username.$domain;// Concatenate with the combined operator$username.=$domain;
Incrementing and decrementing variables by 1 are so common that
these operations have their own operators. The ++
operator adds 1 to a variable, and the -- operator
subtracts 1. These operators are usually used in for() loops, which are detailed in Chapter 3. But
you can use them on any variable holding a number, as shown in Example 2-20.
// Add 1 to $birthday$birthday=$birthday+1;// Add another 1 to $birthday++$birthday;// Subtract 1 from $years_left$years_left=$years_left-1;// Subtract another 1 from $years_left--$years_left;
Frequently, you print the values of variables combined with other
text, such as when you display an HTML table with calculated values in
the cells or a user profile page that shows a particular user’s
information in a standardized HTML template. Double-quoted strings and
here documents have a property that makes this easy: you can
interpolate variables into them. This means
that if the string contains a variable name, the variable name is
replaced by the value of the variable. In Example 2-21, the value of $email is
interpolated into the printed string.
='jacob@example.com';"Send replies to:";
Example 2-21 prints:
Send replies to: jacob@example.com
Here documents are especially useful for interpolating many variables into a long block of HTML, as shown in Example 2-22.
$page_title='Menu';$meat='pork';$vegetable='bean sprout';<<<MENU<html><head><title>$page_title</title></head><body><ul><li> Barbecued $meat<li> Sliced $meat<li> Braised $meat with $vegetable</ul></body></html>MENU;
Example 2-22 prints:
<html> <head><title>Menu</title></head> <body> <ul> <li> Barbecued pork <li> Sliced pork <li> Braised pork with bean sprout </ul> </body> </html>
When you interpolate a variable into a string in a place where the
PHP engine could be confused about the variable name, surround the
variable with curly braces to remove the confusion.
Example 2-23 needs curly braces so that
$preparation is interpolated properly.
$preparation='Braise';$meat='Beef';"{$preparation}d$meatwith Vegetables";
Example 2-23 prints:
Braised Beef with Vegetables
Without the curly braces, the print statement in Example 2-23 would be print
"$preparationd $meat with Vegetables";. In that
statement, it looks like the variable to interpolate is named
$preparationd. The curly braces are necessary to
indicate where the variable name stops and the literal string begins.
The curly brace syntax is also useful for interpolating more
complicated expressions and array values, discussed in Chapter 4.
This chapter covered:
printf()
strtolower(), strtoupper(), or ucwords()
substr()
str_replace()
<? php print 'How are you?'; print 'I'm fine.'; ??>
$first_name to your first name and
$last_name to your last name. Print out a string
containing your first and last name separated by a space. Also print
out the length of that string.
++) and the combined multiplication operator
(*=) to print out the numbers from 1 to 5 and
powers of 2 from 2 (21) to 32 (25).
1 You may also see echo used in some PHP programs to print text. It
works just like print.