BUY THIS BOOK
Add to Cart

Print Book $29.95


Add to Cart

PDF $23.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £20.95

What is this?

Looking to Reprint or License this content?


Learning PHP 5
Learning PHP 5

By David Sklar
Book Price: $29.95 USD
£20.95 GBP
PDF Price: $23.99

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Orientation and First Steps
There are lots of great reasons to write computer programs in PHP. Maybe you want to learn PHP because you need to put together a small web site for yourself that has some interactive elements. Perhaps PHP is being used where you work and you have to get up to speed. This chapter provides context for how PHP fits into the puzzle of web site construction: what it can do and why it's so good at what it does. You'll also get your first look at the PHP language and see it in action.
PHP is a programming language that's used mostly for building web sites. Instead of a PHP program running on a desktop computer for the use of one person, it typically runs on a web server and is accessed by lots of people using web browsers on their own computers. This section explains how PHP fits into the interaction between a web browser and a web server.
When you sit down at your computer and pull up a web page using a browser such as Internet Explorer or Mozilla, you cause a little conversation to happen over the Internet between your computer and another computer. This conversation and how it makes a web page appear on your screen is illustrated in Figure 1-1.
Figure 1-1: Client and server communication without PHP
Here's what's happening in the numbered steps of the diagram:
  1. You type www.example.com/catalog.html into the location bar of Internet Explorer.
  2. Internet Explorer sends a message over the Internet to the computer named www.example.com asking for the /catalog.html page.
  3. Apache, a program running on the www.example.com computer, gets the message and reads the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
PHP's Place in the Web World
PHP is a programming language that's used mostly for building web sites. Instead of a PHP program running on a desktop computer for the use of one person, it typically runs on a web server and is accessed by lots of people using web browsers on their own computers. This section explains how PHP fits into the interaction between a web browser and a web server.
When you sit down at your computer and pull up a web page using a browser such as Internet Explorer or Mozilla, you cause a little conversation to happen over the Internet between your computer and another computer. This conversation and how it makes a web page appear on your screen is illustrated in Figure 1-1.
Figure 1-1: Client and server communication without PHP
Here's what's happening in the numbered steps of the diagram:
  1. You type www.example.com/catalog.html into the location bar of Internet Explorer.
  2. Internet Explorer sends a message over the Internet to the computer named www.example.com asking for the /catalog.html page.
  3. Apache, a program running on the www.example.com computer, gets the message and reads the catalog.html file from the disk drive.
  4. Apache sends the contents of the file back to your computer over the Internet as a response to Internet Explorer's request.
  5. Internet Explorer displays the page on the screen, following the instructions of the HTML tags in the page.
Every time a browser asks for http://www.example.com/catalog.html, the web server sends back the contents of the same
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What's So Great About PHP?
You may be attracted to PHP because it's free, because it's easy to learn, or because your boss told you that you need to start working on a PHP project next week. Since you're going to use PHP, you need to know a little bit about what makes it special. The next time someone asks you "What's so great about PHP?", use this section as the basis for your answer.
You don't have to pay anyone to use PHP. Whether you run the PHP interpreter on a beat-up 10-year-old PC in your basement or in a room full of million-dollar "enterprise-class" servers, there are no licensing fees, support fees, maintenance fees, upgrade fees, or any other kind of charge.
Most Linux distributions come with PHP already installed. If yours doesn't, or you are using another operating system such as Windows, you can download PHP from http://www.php.net/. Appendix A has detailed instructions on how to install PHP.
As an open source project, PHP makes its innards available for anyone to inspect. If it doesn't do what you want, or you're just curious about why a feature works the way it does, you can poke around in the guts of the PHP interpreter (written in the C programming language) to see what's what. Even if you don't have the technical expertise to do that, you can get someone who does to do the investigating for you. Most people can't fix their own cars, but it's nice to be able to take your car to a mechanic who can pop open the hood and fix it.
You can use PHP with a web server computer that runs Windows, Mac OS X, Linux, Solaris, and many other versions of Unix. Plus, if you switch web server operating systems, you generally don't have to change any of your PHP programs. Just copy them from your Windows server to your Unix server, and they will still work.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
PHP in Action
Ready for your first taste of PHP? This section contains a few program listings and explanations of what they do. If you don't understand everything going on in each listing, don't worry! That's what the rest of the book is for. Read these listings to get a sense of what PHP programs look like and an outline of how they work. Don't sweat the details yet.
When given a program to run, the PHP interpreter pays attention only to the parts of the program between PHP start and end tags. Whatever's outside those tags is printed with no modification. This makes it easy to embed small bits of PHP in pages that mostly contain HTML. The PHP interpreter runs the commands between <?php (the PHP start tag) and ?> (the PHP end tag). PHP pages typically live in files whose names end in .php. Example 1-1 shows a page with one PHP command.
Example 1-1. Hello, World!
<html>
<head><title>PHP says hello</title></head>
<body>
<b>
<?php
print "Hello, World!";
?>
</b>
</body> 
</html>
The output of Example 1-1 is:
<html>
<head><title>PHP says hello</title></head>
<body>
<b>
Hello, World!
</b>
</body> 
</html>
In your web browser, this looks like Figure 1-3.
Figure 1-3: Saying hello with PHP
Printing a message that never changes is not a very exciting use of PHP, however. You could have included the "Hello, World!" message in a plain HTML page with the same result. More useful is printing dynamic data — i.e., information that changes. One of the most common sources of information for PHP programs is the user: the browser displays a form, the user enters information into that and hits the "submit" button, the browser sends that information to the server, and the server finally passes it on to the PHP interpreter where it is available to your program.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Basic Rules of PHP Programs
This section lays out some ground rules about the structure of PHP programs. More foundational than the basics such as "how do I print something" or "how do I add two numbers", these proto-basics are the equivalent of someone telling you that you should read pages in this book from top to bottom and left to right, or that what's important on the page are the black squiggles, not the large white areas.
If you've had a little experience with PHP already or you're the kind of person that prefers playing with all the buttons on your new DVD player before going back and reading in the manual about how the buttons actually work, feel free to skip ahead to Chapter 2 now and flip back here later. If you forge ahead to write some PHP programs of your own, and they're behaving unexpectedly or the PHP interpreter complains of "parse errors" when it tries to run your program, revisit this section for a refresher.
Each of the examples you've already seen in this chapter uses <?php as the PHP start tag and ?> as the PHP end tag. The PHP interpreter ignores anything outside of those tags. Text before the start tag or after the end tag is printed with no interference from the PHP interpreter.
A PHP program can have multiple start and end tag pairs, as shown in Example 1-8.
Example 1-8. Multiple start and end tags
Five plus five is:
<?php print 5 + 5; ?>
<p>
Four plus four is:
<?php
 print 4 + 4;
?>
<p>
<img src="vacation.jpg" alt="My Vacation">
The PHP source code inside each set of <?php ?> tags is processed by the PHP interpreter, and the rest of the page is printed as is. Example 1-8 prints:
Five plus five is:
10<p>
Four plus four is:
8<p>
<img src="vacation.jpg" alt="My Vacation">
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter Summary
Chapter 1 covers:
  • PHP's usage by a web server to create a response or document to send back to the browser.
  • PHP as a server-side language, meaning it runs on the web server. This is in contrast to a client-side language such as JavaScript.
  • What you sign up for when you decide to use PHP: it's free (in terms of money and speech), cross-platform, popular, and designed for web programming.
  • How PHP programs that print information, process forms, and talk to a database appear.
  • Some basics of the structure of PHP programs, such as the PHP start and end tags (<?php and ?>), whitespace, case-sensitivity, and comments.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Working with Text and Numbers
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 interpreter 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 characters, 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
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Text
When they're used in computer programs, pieces of text are called strings. This is because they consist of individual characters, 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.
There are a few ways to indicate a string in a PHP program. The simplest is to surround the string with single quotes:
print 'I would like a bowl of soup.';
print 'chicken';
print '06520';
print '"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.
The output of those four print statements appears all on one line. No linebreaks are added by print.
The single quotes aren't part of the string. They are delimiters, which tell the PHP interpreter 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:
print '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 interpreter 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
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Numbers
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 lists some valid numbers in PHP.
Example 2-15. Numbers
print 56;
print 56.3;
print 56.30;
print 0.774422;
print 16777.216;
print 0;
print -213;
print 1298317;
print -9912111;
print -12.52222;
print 0.00;
Internally, the PHP interpreter 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 interpreter 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 interpreter'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. Section 3.3 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.
Example 2-16. Math operations
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
Variables hold the data that your program manipulates while it runs, such as information about a user that you've loaded from a database or entries that have been typed into an HTML form. In PHP, variables are denoted by $ followed by the variable's name. To assign a value to a variable, use an equals sign (=). This is known as the assignment operator.
$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 must begin with letter or an underscore. The rest of the characters in the variable name may be letters, numbers, or an underscore. Table 2-2 lists some acceptable variable names.
Table 2-2: Acceptable variable names
Acceptable
$size
$drinkSize
$my_drink_size
$_drinks
$drink4you2
Table 2-3 lists some unacceptable variable names and what's wrong with them.
Table 2-3: Unacceptable variable names
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter Summary
Chapter 2 covers:
  • Defining strings in your programs three different ways: with single quotes, with double quotes, and as a here document.
  • Escaping: what it is and what characters need to be escaped in each kind of string.
  • Validating a string by checking its length, removing leading and trailing whitespace from it, or comparing it to another string.
  • Formatting a string with printf( ).
  • Manipulating the case of a string with strtolower( ), strtoupper( ), or ucwords( ).
  • Selecting part of a string with substr( ).
  • Changing part of a string with str_replace( ).
  • Defining numbers in your programs.
  • Doing math with numbers.
  • Storing values in variables.
  • Naming variables appropriately.
  • Using combined operators with variables.
  • Using increment and decrement operators with variables.
  • Interpolating variables in strings.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exercises
  1. Find the errors in this PHP program:
    <? php
    print 'How are you?';
    print 'I'm fine.';
    ??>
  2. Write a PHP program that computes the total cost of this restaurant meal: two hamburgers at $4.95 each, one chocolate milk shake at $1.95, and one cola at 85 cents. The sales tax rate is 7.5%, and you left a pre-tax tip of 16%.
  3. Modify your solution to the previous exercise to print out a formatted bill. For each item in the meal, print the price, quantity, and total cost. Print the pre-tax food and drink total, the post-tax total, and the total with tax and tip. Make sure that prices in your output are vertically aligned.
  4. Write a PHP program that sets the variable $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.
  5. Write a PHP program that uses the increment operator (++) and the combined multiplication operator (*=) to print out the numbers from 1 to 5 and powers of 2 from 2 (21) to 32 (25).
  6. Add comments to the PHP programs you've written for the other exercises. Try both single and multiline comments. After you've added the comments, run the programs to make sure they work properly and your comment syntax is correct.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Making Decisions and Repeating Yourself
Chapter 2 covered the basics of how to represent data in PHP programs. A program full of data is only half complete, though. The other piece of the puzzle is using that data to control how the program runs, taking actions such as:
  • If an administrative user is logged in, print a special menu.
  • Print a different page header if it's after three o'clock.
  • Notify a user if new messages have been posted since she last logged in.
All of these actions have something in common: they make decisions about whether a certain logical condition involving data is true or false. In the first action, the logical condition is "Is an administrative user logged in?" If the condition is true (yes, an administrative user is logged in), then a special menu is printed. The same kind of thing happens in the next example. If the condition "is it after three o'clock?" is true, then a different page header is printed. Likewise, if "Have new messages been posted since the user last logged in?" is true, then the user is notified.
When making decisions, the PHP interpreter boils down an expression into true or false. Section 3.1 explains how the interpreter decides which expressions and values are true and which are false.
Those true and false values are used by language constructs such as if( ) to decide whether to run certain statements in a program. The ins and outs of if( ) are detailed later in this chapter in Section 3.2. Use if( ) and similar constructs any time the outcome of a program depends on some changing conditions.
While true and false are the cornerstones of decision making, usually you want to ask more complicated questions, such as "is this user at least 21 years old?" or "does this user have a monthly subscription to the web site or enough money in their account to buy a daily pass?" Section 3.3, later in this chapter, explains PHP's comparison and logical operators. These help you express whatever kind of decision you need to make in a program, such as seeing whether numbers or strings are greater than or less than each other. You can also chain together decisions into a larger decision that depends on its pieces.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding true and false
Every expression in a PHP program has a truth value: true or false. Sometimes that truth value is important because you use it in a calculation, but sometimes you ignore it. Understanding how expressions evaluate to true or to false is an important part of understanding PHP.
Most scalar values are true. All integers and floating-point numbers (except for 0 and 0.0) are true. All strings are true except for two: a string containing nothing at all and a string containing only the character 0. These four values are false. The special constant false also evaluates to false. Everything else is true.
A variable equal to one of the five false values, or a function that returns one of those values also evaluates to false. Every other expression evaluates to true.
Figuring out the truth value of an expression has two steps. First, figure out the actual value of the expression. Then, check whether that value is true or false. Some expressions have common sense values. The value of a mathematical expression is what you'd get by doing the math with paper and pencil. For example, 7 * 6 equals 42. Since 42 is true, the expression 7 * 6 is true. The expression 5 - 6 + 1 equals 0. Since 0 is false, the expression 5 - 6 + 1 is false.
The same is true with string concatenation. The value of an expression that concatenates two strings is the new, combined string. The expression 'jacob' . '@example.com' equals the string jacob@example.com, which is true.
The value of an assignment operation is the value being assigned. The expression $price = 5 evaluates to 5, since that's what's being assigned to $price. Because assignment produces a result, you can chain assignment operations together to assign the same value to multiple variables:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Making Decisions
With the if( ) construct, you can have statements in your program that are only run if certain conditions are true. This lets your program take different actions depending on the circumstances. For example, you can check that a user has entered valid information in a web form before letting her see sensitive data.
The if( ) construct runs a block of code if its test expression is true. This is demonstrated in Example 3-1.
Example 3-1. Making a decision with if( )
if ($logged_in) {
   print "Welcome aboard, trusted user.";
}
The if( ) construct finds the truth value of the expression inside its parentheses (the test expression). If the expression evaluates to true, then the statements inside the curly braces after the if( ) are run. If the expression isn't true, then the program continues with the statements after the curly braces. In this case, the test expression is just the variable $logged_in. If $logged_in is true (or has a value such as 5, -12.6, or Grass Carp, that evaluates to true), then Welcome aboard, trusted user. is printed.
You can have as many statements as you want in the code block inside the curly braces. However, you need to terminate each of them with a semicolon. This is the same rule that applies to code outside an if( ) statement. You don't, however, need a semicolon after the closing curly brace that encloses the code block. You also don't put a semicolon after the opening curly brace. Example 3-2 shows an if( ) clause that runs multiple statements when its test expression is true.
Example 3-2. Multiple statements in an if( ) code block
print "This is always printed.";
if ($logged_in) {
    print "Welcome aboard, trusted user.";
    print 'This is only printed if $logged_in is true.';
}
print "This is also always printed.";
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building Complicated Decisions
The comparison and logical operators in PHP help you put together more complicated expressions on which an if( ) construct can decide. These operators let you compare values, negate values, and chain together multiple expressions inside one if( ) statement.
The equality operator is = =. It returns true if the two values you test with it are equal. The values can be variables or literals. Some uses of the equality operator are shown in Example 3-6.
Example 3-6. The equality operator
if ($new_messages == 10) {
    print "You have ten new messages.";
}

if ($new_messages == $max_messages) {
    print "You have the maximum number of messages.";
}

if ($dinner == 'Braised Scallops') {
    print "Yum! I love seafood.";
}
The opposite of the equality operator is !=. It returns true if the two values that you test with it are not equal. See Example 3-7.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Repeating Yourself
When a computer program does something repeatedly, it's called looping. This happens a lot — for example, when you want to retrieve a set of rows from a database, print rows of an HTML table, or print elements in an HTML <select> menu. The two looping constructs discussed in this section are while( ) and for( ). Their specifics differ but they each require you to specify the two essential attributes of any loop: what code to execute repeatedly and when to stop. The code to execute is a code block just like what goes inside the curly braces after an if( ) construct. The condition for stopping the loop is a logical expression just like an if( ) construct's test expression.
The while( ) construct is like a repeating if( ). You provide an expression to while( ), just like to if( ). If the expression is true, then a code block is executed. Unlike if( ), however, while( ) checks the expression again after executing the code block. If it's still true, then the code block is executed again (and again, and again, as long as the expression is true.) Once the expression is false, program execution continues with the lines after the code block. As you have probably guessed, your code block should do something that changes the outcome of the test expression so that the loop doesn't go on forever.
Example 3-16 uses while( ) to print out an HTML form <select> menu with 10 choices.
Example 3-16. Printing a <select> menu with while( )
$i = 1;
print '<select name="people">';
while ($i <= 10) {
    print "<option>$i</option>\n";
    $i++;
}
print '</select>';
Example 3-16 prints:
<select name="people"><option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter Summary
Chapter 3 covers:
  • Evaluating an expression's truth value: true or false.
  • Making a decision with if( ).
  • Extending if( ) with else.
  • Extending if( ) with elseif( ).
  • Putting multiple statements inside an if( ), elseif( ), or else code block.
  • Using the equality (= =) and not-equals (!=) operators in test expressions.
  • Distinguishing between assignment (=) and equality comparison (= =).
  • Using the less-than (<), greater-than (>), less-than-or-equal-to (<=), and greater-than-or-equal-to (>=) operators in test expressions.
  • Comparing two floating-point numbers with abs( ).
  • Comparing two strings with operators.
  • Comparing two strings with strcmp( ) or strcasecmp( ).
  • Using the negation operator (!) in test expressions.
  • Using the logical operators (&& and ||) to build more complicated test expressions.
  • Repeating a code block with while( ).
  • Repeating a code block with for( ).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exercises
  1. Without using a PHP program to evaluate them, determine whether each of these expressions is true or false:
    1. 100.00 - 100
    2. "zero"
    3. "false"
    4. 0 + "true"
    5. 0.000
    6. "0.0"
    7. strcmp("false","False")
  2. Without running it through the PHP interpreter, figure out what this program prints.
    $age = 12;
    $shoe_size = 13;
    if ($age > $shoe_size) {
        print "Message 1.";
    } elseif (($shoe_size++) && ($age > 20)) {
        print "Message 2.";
    } else {
        print "Message 3.";
    }
    print "Age: $age. Shoe Size: $shoe_size";
  3. Use while( ) to print out a table of Fahrenheit and Celsius temperature equivalents from -50 degrees F to 50 degrees F in 5-degree increments. On the Fahrenheit temperature scale, water freezes at 32 degrees and boils at 212 degrees. On the Celsius scale, water freezes at 0 degrees and boils at 100 degrees. So, to convert from Fahrenheit to Celsius, you subtract 32 from the temperature, multiply by 5, and divide by 9. To convert from Celsius to Fahrenheit, you multiply by 9, divide by 5, and then add 32.
  4. Modify your answer to Exercise 3 to use for( ) instead of while( ).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Working with Arrays
Arrays are collections of related values, such as the data submitted from a form, the names of students in a class, or the populations of a list of cities. In Chapter 2, you learned that a variable is a named container that holds a value. An array is a container that holds multiple values, each distinct from the rest.
This chapter shows you how to work with arrays. Section 4.1, next, goes over fundamentals such as how to create arrays and manipulate their elements. Frequently, you'll want to do something with each element in an array, such as print it or inspect it for certain conditions. Section 4.2 explains how to do these things with the foreach( ) and for( ) constructs. Section 4.3 introduces the implode( ) and explode( ) functions, which turn arrays into strings and strings into arrays. Another kind of array modification is sorting, which is discussed in Section 4.4. Last, Section 4.5 explores arrays that themselves contain other arrays.
Chapter 6 shows you how to process form data, which the PHP interpreter automatically puts into an array for you. When you retrieve information from a database as described in Chapter 7, that data is often packaged into an array.
An array is made up of elements. Each element has a key and a value. An array holding information about the colors of vegetables has vegetable names for keys and colors for values, shown in Figure 4-1.
Figure 4-1: Keys and values
An array can only have one element with a given key. In the vegetable color array, there can't be another element with the key corn even if its value is blue. However, the same value can appear many times in one array. You can have orange carrots, orange tangerines, and orange oranges.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Array Basics
An array is made up of elements. Each element has a key and a value. An array holding information about the colors of vegetables has vegetable names for keys and colors for values, shown in Figure 4-1.
Figure 4-1: Keys and values
An array can only have one element with a given key. In the vegetable color array, there can't be another element with the key corn even if its value is blue. However, the same value can appear many times in one array. You can have orange carrots, orange tangerines, and orange oranges.
Any string or number value can be an array element key such as corn, 4, -36, or Salt Baked Squid. Arrays and other nonscalar values can't be keys, but they can be element values. An element value can be a string, a number, true, or false; it can also be another array.
To create an array, assign a value to a particular array key. Array keys are denoted with square brackets, as shown in Example 4-1.
Example 4-1. Creating arrays
// An array called $vegetables with string keys
$vegetables['corn'] = 'yellow';
$vegetables['beet'] = 'red';
$vegetables['carrot'] = 'orange';

// An array called $dinner with numeric keys
$dinner[0] = 'Sweet Corn and Asparagus';
$dinner[1] = 'Lemon Chicken';
$dinner[2] = 'Braised Bamboo Fungus';

// An array called $computers with numeric and string keys
$computers['trs-80'] = 'Radio Shack';
$computers[2600] = 'Atari';
$computers['Adam'] = 'Coleco';
The array keys and values in Example 4-1 are strings (such as corn, Braised Bamboo Fungus, and Coleco) and numbers (such as 0, 1, and 2600). They are written just like other strings and numbers in PHP programs: with quotes around the strings but not around the numbers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Looping Through Arrays
One of the most common things to do with an array is to consider each element in the array individually and process it somehow. This may involve incorporating it into a row of an HTML table or adding its value to a running total.
The easiest way to iterate through each element of an array is with foreach( ) . The foreach( ) construct lets you run a code block once for each element in an array. Example 4-7 uses foreach( ) to print an HTML table containing each element in an array.
Example 4-7. Looping with foreach( )
$meal = array('breakfast' => 'Walnut Bun',
              'lunch' => 'Cashew Nuts and White Mushrooms',
              'snack' => 'Dried Mulberries',
              'dinner' => 'Eggplant with Chili Sauce');
print "<table>\n";
foreach ($meal as $key => $value) {
    print "<tr><td>$key</td><td>$value</td></tr>\n";
}
print '</table>';
Example 4-7 prints:
<table>
<tr><td>breakfast</td><td>Walnut Bun</td></tr>
<tr><td>lunch</td><td>Cashew Nuts and White Mushrooms</td></tr>
<tr><td>snack</td><td>Dried Mulberries</td></tr>
<tr><td>dinner</td><td>Eggplant with Chili Sauce</td></tr>
</table>
For each element in $meal, foreach( ) copies the key of the element into $key and the value into $value. Then, it runs the code inside the curly braces. In Example 4-7, that code prints $key and $value with some HTML to make a table row. You can use whatever variable names you want for the key and value inside the code block. If the variable names were in use before the foreach( ), though, they're overwritten with values from the array.
When you're using foreach( ) to print out data in an HTML table, often you want to apply alternating colors or styles to each table row. This is easy to do when you store the alternating color values in a separate array. Then, switch a variable between 0 and 1 each time through the foreach( )
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Modifying Arrays
You can operate on individual array elements just like regular scalar variables, using arithmetic, logical, and other operators. Example 4-17 shows some operations on array elements.
Example 4-17. Operating on array elements
$dishes['Beef Chow Foon'] = 12;
$dishes['Beef Chow Foon']++;
$dishes['Roast Duck'] = 3;

$dishes['total'] = $dishes['Beef Chow Foon'] + $dishes['Roast Duck'];

if ($dishes['total']> 15) {
    print "You ate a lot: ";
}

print 'You ate ' . $dishes['Beef Chow Foon'] . ' dishes of Beef Chow Foon.';
Example 4-17 prints:
You ate a lot: You ate 13 dishes of Beef Chow Foon.
Interpolating array element values in double-quoted strings or here documents is similar to interpolating numbers or strings. The easiest way is to include the array element in the string, but don't put quotes around the element key. This is shown in Example 4-18.
Example 4-18. Interpolating array element values in double-quoted strings
$meals['breakfast'] = 'Walnut Bun';
$meals['lunch'] = 'Eggplant with Chili Sauce';
$amounts = array(3, 6);

print "For breakfast, I'd like $meals[breakfast] and for lunch, ";
print "I'd like $meals[lunch]. I want $amounts[0] at breakfast and ";
print "$amounts[1] at lunch.";
Example 4-18 prints:
For breakfast, I'd like Walnut Bun and for lunch,
I'd like Eggplant with Chili Sauce. I want 3 at breakfast and 
6 at lunch.
The interpolation in Example 4-18 works only with array keys that consist exclusively of letters, numbers, and underscores. If you have an array key that has whitespace or other punctuation in it, interpolate it with curly braces, as demonstrated in Example 4-19.
Example 4-19. Interpolating array element values with curly braces
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Sorting Arrays
There are several ways to sort arrays. Which function to use depends on how you want to sort your array and what kind of array it is.
The sort( ) function sorts an array by its element values. It should only be used on numeric arrays, because it resets the keys of the array when it sorts. Example 4-23 shows some arrays before and after sorting.
Example 4-23. Sorting with sort( )
$dinner = array('Sweet Corn and Asparagus',
                'Lemon Chicken',
                'Bra