Understanding PHP Basics - PHP - PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies (2013)

PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies (2013)

Book IV: PHP

Chapter 1: Understanding PHP Basics

In This Chapter

arrow.png Adding PHP sections to HTML files

arrow.png Writing PHP statements

arrow.png Using PHP variables and constants

arrow.png Using arrays

arrow.png Documenting your scripts

PHP is a scripting language designed specifically for use on the web. It has features to aid you in programming the tasks needed to develop dynamic web applications.

In this chapter, we describe the basics of writing PHP scripts — the rules that apply to all PHP statements. Consider these rules similar to general grammar and punctuation rules. In the remaining chapters in this minibook, you find out about specific PHP statements and features and how to write PHP scripts to perform specific tasks.

While this chapter is quite long, you’ve already been exposed to programming through the previous minibook’s look at JavaScript. The chapter starts out with the basics and progresses into more complex material. Even if you’ve had some experience with PHP before, it’s a good idea to start the chapter from the beginning.

How PHP Works

The PHP software works with the web server, which is the software that delivers web pages to the world. When you type a URL into your web browser’s address bar, you’re sending a message to the web server at that URL, asking it to send you an HTML file. The web server responds by sending the requested file. Your browser reads the HTML file and displays the web page. You also request a file from the web server when you click a link in a web page. In addition, the web server processes a file when you click a web page button that submits a form. This process is essentially the same when PHP is installed. You request a file, the web server happens to be running PHP, and it sends HTML back to the browser, thanks to the programming in PHP.


technicalstuff.eps How the web server processes PHP files

When a browser is pointed to a regular HTML file with an .html or .htm extension, the web server sends the file, as is, to the browser. The browser processes the file and displays the web page described by the HTML tags in the file. When a browser is pointed to a PHP file (with a .php extension), the web server looks for PHP sections in the file and processes them or, more exactly, hands them to the PHP processor, instead of just sending them as is to the browser. The web server/PHP processor processes the PHP file as follows:

1. The web server starts scanning the file in HTML mode. It assumes the statements are HTML and sends them to the browser without any processing.

2. The web server continues in HTML mode until it encounters a PHP opening tag (<?php).

3. When it encounters a PHP opening tag, the web server hands the processing over to the PHP module. This is sometimes called escaping from HTML. The web server then assumes that all statements are PHP statements and uses the PHP module to execute the PHP statements. If there is output from PHP, the server sends the output to the browser.

4. The web server continues in PHP mode until it encounters a PHP closing tag (?>).

5. When the web server encounters a PHP closing tag, it returns to HTML mode. It resumes scanning, and the cycle continues from Step 1.


More specifically, when PHP is installed, the web server is configured to expect certain file extensions to contain PHP language statements. Often the extension is .php or .phtml, but any extension can be used. (In this book, we assume that .php is the extension for PHP scripts.) When the web server gets a request for a file with the designated extension, it sends the HTML statements as is, but PHP statements are processed by the PHP software before they're sent to the requester.

When PHP language statements are processed, only the output, or anything printed to the screen,is sent by the web server to the web browser. The PHP language statements, those that don't produce any output to the screen, aren't included in the output sent to the browser, so the PHP code is not normally seen by the user. For instance, in this simple PHP statement, <?php is the PHP opening tag, and ?> is the closing tag.

<?php echo "<p>Hello World</p>"; ?>

Here, echo is a PHP instruction that tells PHP to output the upcoming text. The PHP software processes the PHP statement and outputs the following:

<p>Hello World</p>

That regular HTML statement is delivered to the user’s browser. The browser interprets the statement as HTML code and displays a web page with one paragraph — Hello World. The PHP statement isn’t delivered to the browser, so the user never sees any PHP statements. PHP and the web server must work closely together.

PHP isn’t integrated with all web servers but does work with many of the popular web servers. PHP works well with the Apache web server. PHP also works with Microsoft Internet Information Services (IIS) and others.

tip.eps If you can select or influence the selection of the web server used in your organization, select Apache. By itself, Apache is a good choice. It’s free, open source, stable, and popular. It currently powers more than 60 percent of all websites, according to the web server survey at www.netcraft.com. It runs on Windows, Linux, Mac OS, and most flavors of Unix.

Examining the Structure of a PHP Script

PHP is an embedded scripting language when used in web pages. This means that PHP code is embedded in HTML code. You use HTML tags to enclose the PHP language that you embed in your HTML file — the same way that you would use other HTML tags. You create and edit web pages containing PHP the same way that you create and edit regular HTML pages.

The PHP language statements are enclosed in PHP tags with the following form:

<?php ?>

tip.eps Sometimes you can use a shorter version of the PHP tags. You can try using <? and ?> without the php. If short tags are enabled, you can save a little typing. However, if you use short tags, your scripts won't run if they're moved to another web host where PHP short tags are not activated.

PHP processes all statements between the two PHP tags. After the PHP section is processed, it’s discarded. Or if the PHP statements produce output, the PHP section is replaced by the output. The browser doesn’t see the PHP section — the browser sees only its output, if there is any. For more on this process, see the sidebar “How the web server processes PHP files.”

As an example, start with an HTML script that displays Hello World! in the browser window, shown in Listing 1-1. (It's a tradition that the first script you write in any language is the Hello World script. You might have written a Hello World script when you first learned HTML.)

Listing 1-1: The Hello World HTML Script

<!doctype html>

<html>

<head><title>Hello World Script</title></head>

<body>

<p>Hello World!</p>

</body>

</html>

If you open this HTML script in your browser, you see a web page that displays

Hello World!

Listing 1-2 shows a PHP script that does the same thing — it displays Hello World! in a browser window.

Listing 1-2: The Hello World PHP Script

<!doctype html>

<html>

<head><title>Hello World Script</title></head>

<body>

<?php

echo "<p>Hello World!</p>\n";

?>

</body>

</html>

When you run this script, by looking at it in your browser, it displays the same web page as the HTML script in Listing 1-1. But now you’re doing it with PHP!

remember.eps Don’t look at the file directly with your browser. That is, don’t choose File⇒Open File from your browser menu to navigate to the file and click it. You must open the file by typing its URL in the browser’s address bar. If you see the PHP code displayed in the browser window instead of the output that you expect, you might not have started the file with its URL.

In this PHP script, the PHP section is

<?php

echo "<p>Hello World!</p>";

?>

The PHP tags enclose only one statement — an echo statement. The echo statement is a PHP statement that you'll use frequently. The output is simply the text that's included between the double quotes.

When the PHP section is processed, it’s replaced with the output. In this case, the output is

<p>Hello World!</p>

If you replace the PHP section in Listing 1-2 with the preceding output, the script now looks exactly like the HTML script in Listing 1-1. If you open either script in your browser, you see the same web page. If you look at the source code that the browser sees (in the browser, choose View⇒Source), you see the same source code listing for both scripts.

You can have as many PHP sections in a script as you need, with as many HTML sections as you need, including zero PHP or HTML sections. For instance, the following script has two PHP sections and two HTML sections:

<html>

<head><title>Hello World Script</title></head>

<body>

<?php

echo "<p>Hello World!</p>";

?>

<p>This is HTML only.</p>

<?php

echo "<p>Hello World again!</p>";

?>

<p> This is a second HTML section.</p>

</body>

</html>

Looking at PHP Syntax

The PHP section that you add to your HTML file consists of a series of PHP statements. Each PHP statement is an instruction to PHP to do something. For the purposes in this book, we divide PHP statements into simple or complex statements.

technicalstuff.eps The PHP language syntax is similar to the syntax of C, so if you have experience with C, you’ll be comfortable with PHP. PHP is actually simpler than C because it doesn’t include some of the more difficult concepts of C — concepts not required to program websites.

Using simple statements

Simple statements are an instruction to PHP to do one simple action. The echo statement shown in Listing 1-2 is a simple PHP statement that instructs PHP to output the text between the double quotes. PHP simple statements follow these rules:

check PHP statements end with a semicolon or the PHP ending tag. PHP doesn’t notice white space or the end of lines. It continues reading a statement until it encounters a semicolon or the PHP closing tag, no matter how many lines the statement spans.

check PHP statements may be written in either upper- or lowercase. In an echo statement, Echo, echo, ECHO, and eCHo are all the same to PHP. But variable names are case sensitive, just like in JavaScript.

The following is a valid PHP statement that produces the same output as you saw earlier:

<?php echo "<p>Hello World!</p>" ?>

The echo statement is on the same line as the PHP tags. PHP reads the statement until it reaches the closing tag, which PHP sees as the end of the statement. The next example also produces the same output:

<?php

echo "<p>Hello</p>"; echo "<p>World</p>";

?>

This example contains two PHP echo statements on one line, both ending in a semicolon. If you wanted to, you could write the entire PHP section in one long line, as long as you separated statements with semicolons. However, a script written this way would be difficult for people to read.

Using complex statements

Sometimes groups of simple statements are combined into a block. A block is enclosed by curly braces, { and }. A block of statements execute together. A common use of a block is a conditional block, in which statements are executed only when certain conditions are true. For instance, you might want your script to do the following:

if (the sky is blue)

{

put leash on dragon;

take dragon for a walk in the park;

}

These statements are enclosed in curly braces to ensure that they execute as a block. If the sky is blue, both put leash on dragon and take dragon for a walk in the park are executed. If the sky is not blue, neither statement is executed (no leash; no walk), and you have an irritated dragon on your hands.

PHP statements that use blocks, such as if statements (which we explain in Chapter 2 in this minibook), are what we term complex statements. PHP reads the entire complex statement, not stopping at the first semicolon that it encounters. PHP knows to expect one or more blocks and looks for the ending curly brace of the last block in complex statements. Notice that a semicolon appears before the ending brace. This semicolon is required, but no semicolon is required after the ending curly brace.

Writing PHP Code

PHP code must be read by humans, as well as by the PHP software. PHP scripts are written by humans and must be modified, updated, and maintained by humans. The script might need to be modified a year or two in the future when the original programmer has moved on to retirement on a tropical beach. The person who must modify the script needs to be able to read and understand the script, which he or she has never seen before. Consequently, the PHP code must be written in a style that’s easy for humans to comprehend quickly.

In general, each PHP simple statement is written on a single line ending with a semicolon.

When writing blocks of (complex) statements, coding style dictates that you should indent the block statements to clearly show where the block begins and ends. For instance, in the following example of a conditional statement, the simple statements in the block are indented:

if(the sky is blue)

{

put leash on dragon;

take dragon for a walk in the park;

}

PHP doesn’t need the indenting, but it helps humans read the code.

Two styles are used commonly for the placement of the opening curly brace, as follows:

if(the sky is blue)

{

put leash on dragon;

take dragon for a walk in the park;

}

if(the sky is blue) {

put leash on dragon;

take dragon for a walk in the park;

}

Displaying Content in a Web Page

You display content on your web page with echo or print statements; they both do the same thing. An echo or print statement produces output, which is sent to the user's browser. In fact, everywhere that you see echo in this chapter, you could also write print. The browser handles the output as HTML.

The general format of an echo statement is

echo outputitem,outputitem,outputitem,...

where the following rules apply:

check An outputitem can be a number, a string, or a variable (using variables is discussed in the section Using PHP Variables, later in this chapter. A string must be enclosed in quotes.

check List as many outputitems as you need, separated by commas.

Table 1-1 shows some echo statements and their output.

Table 1-1 echo Statements

echo Statement

Output

echo "Hello";

Hello

echo 123;

123

echo "Hello","World!";

HelloWorld!

echo Hello World!;

Not valid; results in an error message

echo "Hello World!";

Hello World!

echo 'Hello World!';

Hello World!

The echo and print statements output a line of text that's sent to a browser. The browser considers the text to be HTML and handles it that way. Therefore, you need to make sure that your output is valid HTML code that describes the web page that you want the user to see.

When you want to display a web page (or part of a web page) by using PHP, you need to consider three parts involved in producing the web page:

check The PHP script: PHP statements that you write.

check The HTML source code: The source code for the web page that you see when you choose View⇒Source in your browser. The source code is the output from the echo or print statements.

check The web page: The web page that your users see. The web page results from the HTML source code.

remember.eps The echo or print statements send exactly what you echo to the browser — no more, no less. If you don't echo any HTML tags, none are sent.

PHP allows some special characters that format output, but they aren't HTML tags. The PHP special characters affect only the output from the echo or print statement — not the display on the web page. For instance, if you want to start a new line in the PHP output or the HTML source code, you must include a special character (\n) that tells PHP to start a new line. However, this special character just starts a new line in the output; it does not send an actual HTML tag to start a new line on the resulting web page. Table 1-2 shows examples of the three parts.

Table 1-2 Stages of Web Page Delivery

echo Statement

HTML Source Code

Web Page Display

echo "Hello World!";

Hello World!

Hello World!

echo "Hello World!"; echo "Here I am!";

Hello World!Here I am!

Hello World!Here I am!

echo "Hello World!\n"; echo "Here I am!";

Hello World!Here I am

Hello World! Here I am!

echo "Hello World!";echo "<br />";echo "Here I am!";

Hello World!<br />Here I am!"

Hello World!Here I am!

echo "Hello"; echo " World!<br />\n";echo "Here I am!";

Hello World!<br />Here I am!"

Hello World!Here I am!

Table 1-2 summarizes the differences between the stages in creating a web page with PHP. To look at these differences more closely, consider the following two print statements:

print "Line 1";

print "Line 2";

If you put these lines in a script, you might expect the web page to display this:

Line 1

Line 2

However, this is not the output that you would get. The web page would display this:

Line 1Line 2

If you look at the source code for the web page, you see exactly what is sent to the browser, which is this:

Line 1Line 2

Notice that the line that is sent to the browser contains exactly the characters that you printed — no more, no less. The character strings that you printed didn't contain any spaces, so no spaces appear between the lines. Also notice that the two lines are printed on the same line. If you want a new line to start, you have to send a signal indicating the start of a new line. To signal that a new line starts here in PHP, print the special character \n. Change the print statements to the following:

print "line 1\n";

print "line 2";

Now you get what you want, right? Well, no. Now you see the following on the web page:

line 1 line 2

If you look at the source code, you see this:

line 1

line 2

So, the \n did its job: It started a new line in the output. However, HTML displays the output on the web page as one line. If you want HTML to display two lines, you must use a tag, such as the <br /> tag. So, change the PHP end-of-line special character to an HTML tag, as follows:

print "line 1<br />";

print "line 2";

Now you see what you want on the web page:

line 1

line 2

If you look at the source code for this output, you see this:

line 1<br />line 2

tip.eps Use \n liberally. Otherwise, your HTML source code will have some really long lines. For instance, if you print a long form, the whole thing might be one long line in the source code, even though it looks fine in the web page. Use \n to break the HTML source code into reasonable lines. It's much easier to examine and troubleshoot the source code if it isn't a mile-long line.

Using PHP Variables

Variables are containers used to hold information. You saw examples of variables in the preceding minibook for JavaScript. PHP variables are defined a little different but the concept is exactly the same. A variable has a name, and information is stored in the variable. For instance, you might name a variable $age and store the number 12 in it. Information stored in a variable can be used later in the script. One of the most common uses for variables is to hold the information that a user types into a form.

In this section, we give you the details on how to properly name and create PHP variables and assign values to them. We also tell you how to use dynamic variables and display values in different types of PHP statements.

Naming a variable

When you’re naming a variable, keep the following rules in mind:

check Identifier: All variable names have a dollar sign ($) in front of them. This tells PHP that it is a variable name.

check Beginning of name: Variable names must begin with a letter or an underscore. They cannot begin with a number.

check Acceptable length: Variable names can be any length.

check Acceptable characters: Variable names can include letters, numbers, and underscores only.

check Case sensitivity: Uppercase and lowercase letters are not the same. For example, $firstname and $Firstname are not the same variable. If you store information in $firstname, for example, you can't access that information by using the variable name $firstName.

tip.eps When you name variables, use names that make it clear what information is in the variable. Using variable names like $var1, $var2, $A, or $B doesn't contribute to the clarity of the script. Although PHP doesn't care what you name the variable and won't get mixed up, people trying to follow the script will have a hard time keeping track of which variable holds what information. Variable names like $firstName, $age, and $orderTotal are much more descriptive and helpful.

Creating and assigning values to variables

Variables can hold numbers or strings of characters. You store information in variables with a single equal sign (=). For instance, the following four PHP statements assign information to variables:

$age = 12;

$price = 2.55;

$number = -2;

$name = "Little Bo Peep";

Notice that the character string is enclosed in quotes, but the numbers are not. We discuss more about using numbers and characters in the section Understanding Data Types, later in this chapter.

Whenever you put information into a variable that didn’t exist before, you create that variable. For instance, suppose you use the following PHP statement:

$firstname = "George";

If this statement is the first time that you've mentioned the variable $firstname, this statement creates the variable and sets it to "George". If you have a previous statement setting $firstname to "Mary", this statement changes the value of $firstname to "George".

You can also remove information from a variable. You might do this in order to clear out information or to initialize the variable. For example, the following statement takes information out of the variable $age:

$age = "";

The variable $age exists but doesn't contain a value. It doesn't mean that $age is set to 0 (zero) because 0 is a value. It means that $age doesn't store any information. It contains a string of length 0.

You can go even further and uncreate the variable by using this statement:

unset($age);

After this statement is executed, the variable $age no longer exists.

Using variable variables

PHP allows you to use dynamic variable names, called variable variables. You can name a variable with the value stored in another variable.

That is, one variable contains the name of another variable. For example, suppose you want to construct a variable named $city with the value Los Angeles. You can use the following statement:

$name_of_the_variable = "city";

This statement creates a variable that contains the name that you want to give to a variable. Then, you use the following statement:

$$name_of_the_variable - "Los Angeles";

Note the extra dollar sign ($) character at the beginning of the variable name. This indicates a variable variable. This statement creates a new variable with the name that is the value in $name_of_the_variable, resulting in the following:

$city = "Los Angeles";

The value of $name_of_the_variable does not change.

The following example shows how this feature works. In its present form, the script statements may not seem that useful; you may see a better way to program this task. The true value of variable variables becomes clear when they are used with arrays and loops, as discussed in Chapter 2of this minibook.

Suppose you want to name a series of variables with the names of cities that have values that are the populations of the cities. You can use this code:

$Reno = 360000;

$Pasadena = 138000;

$cityname = "Reno";

echo "The size of $cityname is ${$cityname}";

$cityname = "Pasadena";

echo "The size of $cityname is ${$cityname}";

The output from this code is

The size of Reno is 360000

The size of Pasadena is 138000

Notice that you need to use curly braces around the variable name in the echo statement so that PHP knows where the variable name is. If you use the statement without the curly braces, the output is as follows:

The size of Reno is $Reno

Without the curly braces in $$cityname, PHP converts $cityname to its value and puts the extra $ in front of it, as part of the preceding string.

Displaying variable values

You can display the value in a variable by using any of the following statements:

check echo

check print

check print_r

check var_dump

Using variables in echo and print statements

You can display the value in a variable on a web page with an echo or print statement. For instance, if you set the $age variable to 12 and then use the following PHP echo statement in a PHP section, the output is 12.

echo $age;

If you include the following line in an HTML file:

<p>Your age is <?php echo $age ?>.</p>

the output on the web page is

Your age is 12.

Table 1-3 shows the use of variables in some print statements and their output. For the purposes of the table, assume that $string1 is set to Hello and $string2 is set to World!.

Table 1-3 print Statements

print Statement

Output

print $string1;

Hello

print $string1,$string2;

HelloWorld!

print "$string1 $string2";

Hello World!

print "Hello ",$string2;

Hello World!

print "Hello"," ",$string2;

Hello World!

print '$string1',"$string2";

$string1World!

warning_bomb.eps Single and double quotes have different effects on variables, as follows.

check Single quotes (' '): When you use single quotes, variable names are echoed as is.

check Double quotes (" "): When you use double quotes, variable names are replaced by the variable values.

Sometimes you need to enclose variable names in curly braces ({ }) to define the variable name. For instance, the following statements won't output bird as the $pet variable.

$pet = "bird";

echo "The $petcage has arrived.";

In other words, the output won't be The birdcage has arrived. Rather, PHP will look for the variable $petcage and won't be able to find it. You can echo the correct output by using curly braces to separate the $pet variable:

$pet = "bird";

echo "The {$pet}cage has arrived.";

The preceding statement gives you

The birdcage has arrived.

Knowing how long a variable holds its value

A variable keeps its information for the entire script, not just for a single PHP section. If a variable is set to "yes" at the beginning of a file, it will still hold "yes" at the end of the page. For instance, suppose your file has the following statements:

<p>Hello World!</p>

<?php

$age = 15;

$name = "Harry";

?>

<p>Hello World again!</p>

<?php

echo $name;

?>

The echo statement in the second PHP section will display Harry. The web page resulting from these statements is

Hello World!

Hello World again!

Harry

Displaying variables with print_r statements

PHP provides a function named print_r for looking at the value in a variable. You can write the following statements to display a variable value:

$weekday = "Monday";

print_r($weekday);

The output from print_r is

Monday

Displaying variables with var_dump statements

PHP provides a function named var_dump that you can use to display a variable value and its data type. (Data types are discussed in detail in the section Understanding Data Types, later in this chapter.)

You can write the following statements to display a variable value:

$weekday = "Monday";

var_dump($weekday);

The output of var_dump is

string(6) "Monday"

The output shows that the value in $weekday is Monday. The output also shows that the value is a string data type that is six characters long.

remember.eps You'll use var_dump frequently for troubleshooting PHP. Its use is essential for that purpose.

Using PHP Constants

PHP constants are similar to variables. Constants are given a name, and a value is stored in them. However, constants are constant; that is, they can't be changed by the script. After you set the value for a constant, it stays the same. If you used a constant for age and set it to 21, for example, the value is always and forever 21.

Constants are used when a value is needed in several places in the script and doesn’t change during the script. The value is set in a constant at the start of the script. By using a constant throughout the script, instead of a variable, you make sure that the value won’t get changed accidentally. By giving it a name, you know what the information is instantly. And by setting a constant once at the start of the script (instead of using the value throughout the script), you can change the value of the constant in one place if needed instead of hunting for the value in many places in the script to change it.

For instance, you might set one constant that’s the company name and another constant that’s the company address and use them wherever needed. Then, if the company moves, you can just change the value in the company address constant at the start of the script instead of having to find and change every place in your script that echoed the company name.

You set constants by using the define statement. The format is

define("constantname","constantvalue");

For instance, to set a constant with the company name, use the following statement:

define("COMPANY","My Fine Company");

Use the constant in your script wherever you need your company name:

echo COMPANY;

remember.eps When you echo a constant, you can’t enclose it in quotes. If you do, you echo the constant name, instead of the value. You can echo it without anything, as shown in the preceding example, or enclosed in parentheses.

You can use any name for a constant that you can use for a variable, as long as you follow these conventions:

check No identifier: Constant names are not preceded by a dollar sign ($).

check Case: By convention, constants are given names that are all uppercase, so you can easily spot constants, but PHP itself doesn’t care what you name a constant. You don’t have to use uppercase; it’s just clearer.

check Characters: You can store either a string or a number in it. The following statement is perfectly okay with PHP:

define ("AGE",29);

Understanding Data Types

Values stored in a variable or a constant are stored as a specific type of data. PHP provides these eight data types:

check Integer: A whole number

check Floating-point number (float): A numeric value with decimal digits

check String: A series of characters

check Boolean: A value that can be either true or false

check NULL: A value that represents no value

check Array: A group of values in one variable

check Object: A structure created with a class

check Resource: A reference that identifies a connection

Here are some things that you need to know about working with data types:

check PHP determines the data type automatically. When writing PHP scripts, you don’t need to specify which data type you’re storing. The following two statements store different data types:

$var1 = 123;

$var2 = "123";

check The value for $var1 is stored as an integer. The value for $var2 is stored as a string because it's enclosed in quotes.

check PHP converts data types automatically when it needs to. For instance, if you add two variables, one containing an integer and one containing a float, PHP converts the integer to a float so that it can add the two.

check You can determine the data type. Occasionally, you might want to store a value as a data type different than the data type PHP automatically stores. You can set the data type for a variable with a cast, as follows:

$var3 = "222";

$var4 = (int) $var3;

check This statement sets $var4 equal to the value in $var3, changing the value from a string to an integer. You can also cast using (float) or (string).

check You can query the data type. You can find out which data type is stored in a variable with var_dump(). For instance, you can display a variable as follows:

var_dump($var4);

check The output from this statement is the following:

int(222)

Integer, float, string, Boolean, and NULL data types are discussed in the following sections. Arrays are discussed in the section Using Arrays, later in this chapter. Objects are discussed in Chapter 4 in this minibook. The Resource data type is a specialty type that you likely won’t directly encounter in day-to-day programming and therefore isn’t covered in this book.

Working with integers and floating-point numbers

Integers are whole numbers, such as 1, 10, and 333. Floating-point numbers, also called real numbers, are numbers that contain a decimal value, such as 3.1 or .667. PHP stores the value as an integer or a float automatically.

Performing arithmetic operations on numeric data types

PHP enables you to do arithmetic operations on numbers. You indicate arithmetic operations with two numbers and an arithmetic operator. For instance, one operator is the plus (+) sign, so you can indicate an arithmetic operation like this:

1 + 2

You can also perform arithmetic operations with variables that contain numbers, as follows:

$n1 = 1;

$n2 = 2;

$sum = $n1 + $n2;

You can add numbers that aren’t the same data type, as follows:

$n1 = 1.5;

$n2 = 2;

$sum = $n1 + $n2;

PHP converts $n2 to a float (2.0) and adds the two values. $sum is then a float.

Using arithmetic operators

PHP provides five arithmetic operators. Table 1-4 shows the arithmetic operators that you can use.

Table 1-4 Arithmetic Operators

Operator

Description

+

Add two numbers.

-

Subtract the second number from the first number.

*

Multiply two numbers.

/

Divide the first number by the second number.

%

Find the remainder when the first number is divided by the second number. This is called modulus. For instance, in $a = 13 % 4, $a is set to 1.

You can do several arithmetic operations at once. For instance, the following statement performs three operations:

$result = 1 + 2 * 4 + 1;

The order in which the arithmetic is performed is important. You can get different results depending on which operation is performed first.

remember.eps PHP does multiplication and division first, followed by addition and subtraction. If other considerations are equal, PHP goes from left to right.

Consequently, the preceding statement sets $result to 10, in the following order:

$result = 1 + 2 * 4 + 1 (First it does the multiplication.)

$result = 1 + 8 + 1 (Next it does the leftmost addition.)

$result = 9 + 1 (Next it does the remaining addition.)

$result = 10

You can change the order in which the arithmetic is performed by using parentheses. The arithmetic inside the parentheses is performed first. For instance, you can write the preceding statement with parentheses like this:

$result = (1 + 2) * 4 + 1;

This statement sets $result to 13, in the following order:

$result = (1 + 2) * 4 + 1 (First it does the math in the parentheses.)

$result = 3 * 4 + 1 (Next it does the multiplication.)

$result = 12 + 1 (Next it does the addition.)

$result = 13

tip.eps On the better-safe-than-sorry principle, it’s best to use parentheses whenever more than one answer is possible.

Formatting numbers as dollar amounts

Often, the numbers that you work with are dollar amounts, such as product prices. You want your customers to see prices in the proper format on web pages. In other words, dollar amounts should always have two decimal places. However, PHP stores and displays numbers in the most efficient format. If the number is 10.00, it's displayed as 10. To put numbers into the proper format for dollars, you can use sprintf. The following statement formats a number into a dollar format:

$newvariablename = sprintf("%01.2f", $oldvariablename);

This statement reformats the number in $oldvariablename and stores it in the new format in $newvariablename, which is a string data type. For example, the following statements display money in the correct format:

$price = 25;

$f_price = sprintf("%01.2f",$price);

echo "$f_price";

You see the following on the web page:

25.00

If you display the variable with var_dump($f_price), the output is

string(5) "25.00"

If you want commas to separate thousands in your number, you can use number_format. The following statement creates a dollar format with commas:

$price = 25000;

$f_price = number_format($price,2);

echo "$f_price";

You see the following on the web page:

25,000.00

tip.eps The 2 in the number_format statement sets the format to two decimal places. You can use any number to get any number of decimal places. Also, you can add a $ in front of the dollar amount in the output like this:

echo "$" . $f_price;

Working with character strings

A character string is a series of characters. Characters are letters, numbers, and punctuation. When a number is used as a character, it is just a stored character, the same as a letter. It can’t be used in arithmetic. For instance, a phone number is stored as a character string because it needs to be only stored — not added or multiplied.

Assigning strings to variables

When you store a character string in a variable, you tell PHP where the string begins and ends by using double quotes or single quotes. For instance, the following two statements produce the same result:

$string = "Hello World!";

$string = 'Hello World!';

However, suppose that you wanted to store a string as follows:

$string = 'It is Sally's house';

echo $string;

These statements won't work because when PHP sees the ' (single quote) after Sally, it thinks that this is the end of the string, displaying the following:

It is Sally

You need to tell PHP to interpret the single quote (') as an apostrophe instead of as the end of the string. You can do this by using a backslash (\) in front of the single quote. The backslash tells PHP that the single quote doesn't have any special meaning; it's just an apostrophe. This is called escaping the character. Use the following statements to display the entire string:

$string = 'It is Sally\'s house';

echo $string;

remember.eps Similarly, when you enclose a string in double quotes, you must also use a backslash in front of any double quotes in the string.

Using single and double quotes with strings

Single-quoted and double-quoted strings are handled differently, as follows:

check Single-quoted strings are stored literally — with the exception of \', which is stored as an apostrophe.

check In double-quoted strings, variables and some special characters are evaluated before the string is stored.

Here are the most important differences in the use of double or single quotes in code:

check Handling variables: If you enclose a variable in double quotes, PHP uses the value of the variable. However, if you enclose a variable in single quotes, PHP uses the literal variable name. For example, if you use the following statements:

$month = 12;

$result1 = "$month";

$result2 = '$month';

echo $result1;

echo "<br />";

echo $result2;

the output is

12

$month

Refer to Table 1-3, earlier in this chapter, for more examples.

check Starting a new line: The special characters \n tell PHP to start a new line. When you use double quotes, PHP starts a new line at \n; with single quotes, \n is a literal string. For instance, when using the following statements:

$string1 = "String in \ndouble quotes";

$string2 = 'String in \nsingle quotes';

the string1 output is

String in

double quotes

and the string2 output is

String in \nsingle quotes

check Inserting a tab: The special characters \t tell PHP to insert a tab. When you use double quotes, PHP inserts a tab at \t, but with single quotes, \t is a literal string. For instance, when using the following statements:

$string1 = "String in \tdouble quotes";

$string2 = 'String in \tsingle quotes';

the string1 output is

String in double quotes

and the string2 output is

String in \tsingle quotes

The quotes that enclose the entire string determine the treatment of variables and special characters, even if other sets of quotes are inside the string. For example, look at the following statements:

$number = 10;

$string1 = "There are '$number' people in line.";

$string2 = 'There are "$number" people waiting.';

echo $string1,"<br />\n";

echo $string2;

The output is as follows:

There are '10' people in line.

There are "$number" people waiting.

Joining strings

You can join strings, a process called concatenation, by using a dot (.). For instance, you can join strings with the following statements:

$string1 = 'Hello';

$string2 = 'World!';

$stringall = $string1.$string2;

echo $stringall;

The echo statement's output is

HelloWorld!

Notice that no space appears between Hello and World. That's because no spaces are included in the two strings that are joined. You can add a space between the words by using the following concatenation statement rather than the earlier statement:

$stringall = $string1." ".$string2;

You can use .= to add characters to an existing string. For example, you can use the following statements in place of the preceding statements:

$stringall = "Hello";

$stringall .= " World!";

echo $stringall;

The echo statement output is this:

Hello World!

You can also take strings apart. You can separate them at a given character or look for a substring in a string. You use functions to perform these and other operations on a string. We explain functions in Chapter 2 in this minibook.

Storing really long strings

PHP provides a feature called a heredoc that is useful for assigning values that consist of really long strings that span several lines. A heredoc enables you to tell PHP where to start and end reading a string. A heredoc statement has the following format:

$varname = <<<ENDSTRING

text

ENDSTRING;

ENDSTRING can include any string you want to use, as you'll see later. You enclose the text you want stored in the variable $varname by typing ENDSTRING at the beginning and again at the end. When PHP processes the heredoc, it reads the first ENDSTRING and knows to start reading text into$varname. It continues reading text into $varname until it encounters the same ENDSTRING again. At that point, it ends the string. The string created by a heredoc statement evaluates variables and special characters in the same manner as a double-quoted string.

The following statements create a string with the heredoc method:

$distance = 10;

$herevariable = <<<ENDOFTEXT

The distance between

Los Angeles and Pasadena

Is $distance miles.

ENDOFTEXT;

echo $herevariable;

The output of the echo statement is as follows:

The distance between Los Angeles and Pasadena is 10 miles.

warning_bomb.eps But be careful. PHP is picky about its ENDSTRINGs. When it first appears, the ENDSTRING (ENDOFTEXT in this example) must occur at the end of the first line, with nothing following it, not even a space. And the ENDSTRING on the last line must occur at the start of the line, with nothing before it, not even a space and nothing following it other than the semicolon. If these rules are broken, PHP won't recognize the ending string and will continue looking for it throughout the rest of the script. It will eventually display a parse error showing a line number that is the last line in the script.

Working with the Boolean data type

A Boolean data type takes on only the values of true or false. You can assign a Boolean value to a variable as follows:

$var1 = true;

PHP sets the variable to a Boolean data type. Boolean values are used when comparing values and expressions for conditional statements, such as if statements. Comparing values is discussed in detail in Chapter 2 in this minibook.

The following values are evaluated as false by PHP:

check The word false

check The integer 0

check The floating-point number 0.0

check An empty string

check A string with the value 0

check An empty array

check An empty object

check The value NULL

If a variable contains a value that is not evaluated as false, it is assigned the value true.

Working with the NULL data type

The only value that is a NULL data type is NULL. You can assign the value to a variable as follows:

$var1 = NULL;

A variable with a NULL value contains no value.

Using Arrays

Arrays are complex variables. An array stores a group of values under a single variable name, and it's useful for storing related values. For instance, you can store information about a flower (such as variety, color, and cost) in a single array named $flowerinfo. Information in an array can be handled, accessed, and modified easily. For instance, PHP has several methods for sorting an array. The following sections give you the lowdown on arrays.

Creating arrays

The simplest way to create an array is to assign a value to a variable with square brackets ([ ]) at the end of its name. For instance, assuming that you haven't referenced $cities at any earlier point in the script, the following statement creates an array called $cities:

$cities[1] = "Phoenix";

At this point, the array named $cities has been created and has only one value: Phoenix. Next, you use the following statements:

$cities[2] = "Tucson";

$cities[3] = "Flagstaff";

Now the array $cities contains three values: Phoenix, Tucson, and Flagstaff.

An array can be viewed as a list of key/value pairs. Each key/value pair is called an element. To get a particular value, you specify the key in the brackets. In the preceding array, the keys are numbers — 1, 2, and 3. However, you can also use words for keys. For instance, the following statements create an array of state capitals:

$capitals['CA'] = "Sacramento";

$capitals['TX'] = "Austin";

$capitals['OR'] = "Salem";

You can use shortcuts rather than write separate assignment statements for each number. One shortcut uses the following statements:

$cities[] = "Phoenix";

$cities[] = "Tucson";

$cities[] = "Flagstaff";

When you create an array using this shortcut, the values are automatically assigned keys that are serial numbers, starting with the number 0. For example, the following statement outputs Phoenix.

echo "$cities[0]";

warning_bomb.eps The first value in an array with a numbered index is 0 unless you deliberately set it to a different number. One common mistake when working with arrays is to think of the first number as 1 rather than 0.

An even better shortcut is to use the following statement:

$cities = array( "Phoenix","Tucson","Flagstaff");

This statement creates the same array, with numbered keys, as the preceding shortcut. You can use a similar statement to create arrays with words as keys. For example, the following statement creates the array of state capitals:

$capitals = array( "CA" => "Sacramento", "TX" => "Austin",

"OR" => "Salem" );

Viewing arrays

You can echo an array value like this:

echo $capitals['TX'];

If you include the array value in a longer echo statement enclosed by double quotes, you might need to enclose the array value name in curly braces:

echo "The capital of Texas is {$capitals['TX']}<br />";

You can see the structure and values of any array by using a print_r or a var_dump statement. To display the $capitals array, use one of the following statements:

print_r($capitals);

var_dump($capitals);

This print_r statement provides the following output:

Array

(

[CA] => Sacramento

[TX] => Austin

[OR] => Salem

)

The var_dump statement provides the following output:

array(3) {

["CA"]=>

string(10) "Sacramento"

["TX"]=>

string(6) "Austin"

["OR"]=>

string(5) "Salem"

}

The print_r output shows the key and the value for each element in the array. The var_dump output shows the data type, as well as the keys and values.

tip.eps When you display the output from print_r or var_dump on a web page, it displays with HTML, which means that it displays in one long line. To see the output on the web in the useful format that we describe here, send HTML tags that tell the browser to display the text as received, without changing it, by using the following statements:

echo "<pre>";

print_r($capitals);

echo "</pre>";

Removing values from arrays

Sometimes you need to completely remove an element from an array. For example, suppose you have the following array with five elements:

$cities[0] = "Phoenix";

$cities[1] = "Tucson";

$cities[2] = "Flagstaff";

$cities[3] = "Tempe";

$cities[4] = "Prescott";

Now you decide that you no longer want to include Tempe, so you use the following statement to try to remove Tempe from the array:

$cities[3] = "";

Although this statement sets $cities[3] to an empty string, it doesn't remove the element from the array. You still have an array with five elements, but one of the five values is empty. To totally remove the element from the array, you need to unset it with the following statement:

unset($cities[3]);

Now your array has only four elements in it, as follows:

$cities[0] = "Phoenix";

$cities[1] = "Tucson";

$cities[2] = "Flagstaff";

$cities[4] = "Prescott";

Sorting arrays

One of the most useful features of arrays is that PHP can sort them for you. PHP originally stores array elements in the order in which you create them. If you display the entire array without changing the order, the elements will be displayed in the order in which you created them. Often, you want to change this order. For example, you might want to display the array in alphabetical order by value or by key.

PHP can sort arrays in a variety of ways. To sort an array that has numbers as keys, use a sort function, as follows:

sort($cities);

This statement sorts by the values and assigns new keys that are the appropriate numbers. The values are sorted with numbers first, uppercase letters next, and lowercase letters last. For instance, consider the $cities array created in the preceding section:

$cities[0] = "Phoenix";

$cities[1] = "Tucson";

$cities[2] = "Flagstaff";

After the following sort statement

sort($cities);

the array becomes

$cities[0] = "Flagstaff";

$cities[1] = "Phoenix";

$cities[2] = "Tucson";

warning_bomb.eps If you use sort() to sort an array with words as keys, the keys will be changed to numbers, and the word keys will be thrown away.

To sort arrays that have words for keys, use the asort function. This statement sorts the capitals by value and keeps the original key for each value. For instance, consider the state capitals array created in the preceding section:

$capitals['CA'] = "Sacramento";

$capitals['TX'] = "Austin";

$capitals['OR'] = "Salem";

After the following asort statement

asort($capitals);

the array becomes

$capitals['TX'] = "Austin";

$capitals['CA'] = "Sacramento";

$capitals['OR'] = "Salem";

Notice that the keys stayed with the value when the elements were reordered. Now the elements are in alphabetical order, and the correct state key is still with the appropriate state capital. If the keys had been numbers, the numbers would now be in a different order. It's unlikely that you want to use asort on an array with numbers as a key.

Several other sort statements sort in other ways. Table 1-5 lists all the available sort statements.

Table 1-5 Ways You Can Sort Arrays

Sort Statement

What It Does

sort($arrayname)

Sorts by value; assigns new numbers as the keys.

asort($arrayname)

Sorts by value; keeps the same key.

rsort($arrayname)

Sorts by value in reverse order; assigns new numbers as the keys.

arsort($arrayname)

Sorts by value in reverse order; keeps the same key.

ksort($arrayname)

Sorts by key.

krsort($arrayname)

Sorts by key in reverse order.

usort($arrayname,functionname)

Sorts by a function. (See the next chapter.)

Getting values from arrays

You can retrieve any individual value in an array by accessing it directly, as follows:

$CAcapital = $capitals['CA'];

echo $CAcapital ;

The output from these statements is

Sacramento

If you use an array element that doesn’t exist, a notice is displayed. (Read about notices in the section Understanding PHP Error Messages, later in this chapter.) For example, suppose that you use the following statement:

$CAcapital = $capitals['CAx'];

If the array $capitals exists but no element has the key CAx, you see the following notice:

Notice: Undefined index: CAx in d:\testarray.php on line 9

A notice doesn't cause the script to stop. Statements after the notice continue to execute. But because no value has been put into $CAcapital, any subsequent echo statements will echo a blank space. You can prevent the notice from being displayed by using the @ symbol:

@$CAcapital = $capitals['CAx'];

You can get several values at once from an array using the list statement or all the values from an array by using the extract statement.

The list function gets values from an array and puts them into variables. The following statements include a list statement:

$flowerInfo = array ("Rose", "red", 12.00);

list($firstvalue,$secondvalue) = $flowerInfo;

echo $firstvalue,"<br />";

echo $secondvalue,"<br />";

The first line creates the $flowerInfo array. The third line sets up two variables named $firstvalue and $secondvalue and copies the first two values in $flowerInfo into the two new variables, as if you had used the two statements

$firstvalue=$flowerInfo[0];

$secondvalue=$flowerInfo[1];

The third value in $flowerInfo isn't copied into a variable because the list statement includes only two variables. The output from the echo statements is

Rose

red

You can retrieve all the values from an array with words as keys by using extract. Each value is copied into a variable named for the key. For instance, suppose the $flowerinfo array is created as follows:

$flowerInfo = array ("variety"=>"Rose", "color"=>"red", "cost"=>12.00);

The following statements get all the information from $flowerInfo and echo it:

extract($flowerInfo);

echo "variety is $variety; color is $color; cost is $cost";

The output for these statements is

variety is Rose; color is red; cost is 12.00;

Walking through an array

You will often want to do something to every value in an array. You might want to echo each value, store each value in the database, or add 6 to each value in the array. In technical talk, walking through each and every value in an array, in order, is iteration. It’s also sometimes calledtraversing. Here are two ways to walk through an array:

check Manually: Move a pointer from one array value to another.

check Using foreach: Automatically walk through the array, from beginning to end, one value at a time.

Manually walking through an array

You can walk through an array manually by using a pointer. To do this, think of your array as a list. Imagine a pointer pointing to a value in the list. The pointer stays on a value until you move it. After you move it, it stays there until you move it again. You can move the pointer with the following instructions:

check current($arrayname): Refers to the value currently under the pointer; doesn't move the pointer.

check next($arrayname): Moves the pointer to the value after the current value.

check previous($arrayname): Moves the pointer to the value before the current pointer location.

check end($arrayname): Moves the pointer to the last value in the array.

check reset($arrayname): Moves the pointer to the first value in the array.

The following statements manually walk through an array containing state capitals:

$value = current ($capitals);

echo "$value<br />";

$value = next ($capitals);

echo "$value<br />";

$value = next ($capitals);

echo "$value<br />";

Unless you've moved the pointer previously, it's located at the first element when you start walking through the array. If you think that the array pointer might have been moved earlier in the script or if your output from the array seems to start somewhere in the middle, use the resetstatement before you start walking, as follows:

reset($capitals);

When using this method to walk through an array, you need an assignment statement and an echo statement for every value in the array — for each of the 50 states. The output is a list of all the state capitals.

This method gives you flexibility. You can move through the array in any manner — not just one value at a time. You can move backwards, go directly to the end, skip every other value by using two next statements in a row, or whatever method is useful. However, if you want to go through the array from beginning to end, one value at a time, PHP provides foreach, which does exactly what you need much more efficiently. foreach is described in the next section.

Using foreach to walk through an array

The foreach statement walks through the array one value at a time. The current key and value of the array can be used in the block of statements each time the block executes. The general format is

foreach( $arrayname as $keyname => $valuename )

{

block of statements;

}

Fill in the following information:

check arrayname: The name of the array that you're walking through.

check keyname: The name of the variable where you want to store the key. keyname is optional. If you leave out $keyname =>, only the value is put into a variable that can be used in the block of statements.

check valuename: The name of the variable where you want to store the value.

For instance, the following foreach statement walks through the sample array of state capitals and echoes a list:

$capitals = array("CA" => "Sacramento", "TX" => "Austin",

"OR" => "Salem" );

ksort($capitals);

foreach( $capitals as $state => $city )

{

echo "$city, $state<br />";

}

The preceding statements give the following web page output:

Sacramento, CA

Salem, OR

Austin, TX

You can use the following line in place of the foreach line in the previous statements:

foreach( $capitals as $city )

When using this foreach statement, only the city is available for output. You would then use the following echo statement:

echo "$city<br />";

The output with these changes is

Sacramento

Salem

Austin

When foreach starts walking through an array, it moves the pointer to the beginning of the array. You don't need to reset an array before walking through it with foreach.

Storing values with multidimensional arrays

In the earlier sections of this chapter, we describe arrays that are a single list of key/value pairs. However, on some occasions, you might want to store values with more than one key. For instance, suppose you want to store cities by state and county, as follows:

$cities['AZ']['Maricopa'] = Phoenix;

$cities['AZ']['Cochise'] = Tombstone;

$cities['AZ']['Yuma'] = Yuma;

$cities['OR']['Multnomah'] = Portland;

$cities['OR']['Tillamook'] = Tillamook;

$cities['OR']['Wallowa'] = Joseph;

This kind of array is a multidimensional array because it’s like an array of arrays with the following structure:

$cities key value

key value

AZ Maricopa Phoenix

Cochise Tombstone

Yuma Yuma

OR Multnomah Portland

Tillamook Tillamook

Wallowa Joseph

$cities is a two-dimensional array.

warning_bomb.eps PHP can also understand multidimensional arrays that are four, five, six, or more levels deep. However, people tend to get headaches when they try to comprehend an array that’s more than three levels deep. The possibility of confusion increases when the number of dimensions increases. Try to keep your multidimensional arrays manageable.

You can get values from a multidimensional array by using the same procedures that you use with a one-dimensional array. For instance, you can access a value directly with this statement:

$city = $cities['AZ']['Yuma'];

You can also echo the value:

echo $cities['OR']['Wallowa'];

However, if you combine the value within double quotes, you need to use curly braces to enclose the variable name. The $ that begins the variable name must follow the { immediately, without a space, as follows:

echo "A city in Multnomah County, Oregon, is {$cities['OR']['Multnomah']}";

The output is

A city in Multnomah County, Oregon, is Portland

You can walk through a multidimensional array by using foreach statements (described in the preceding section). You need a foreach statement for each array. One foreach statement is inside the other foreach statement. Putting statements inside other statements is called nesting.

Because a two-dimensional array, such as $cities, contains two arrays, it takes two foreach statements to walk through it. The following statements get the values from the multidimensional array and output them in an HTML table:

foreach( $cities as $state )

{

foreach( $state as $county => $city )

{

echo "$city, $county county <br />";

}

}

The first foreach statement walks through the $cities multidimensional array and stores an array with the key/value pair of county/city in the variable $state. The second foreach statement walks through the array stored in $state. These statements give you the following output:

Phoenix, Maricopa county

Tombstone, Cochise county

Yuma, Yuma county

Portland, Multnomah county

Tillamook, Tillamook county

Joseph, Wallowa county

Using Dates and Times

Dates and times can be important elements in a web database application. PHP has the capability to recognize dates and times and handle them differently than plain character strings. Dates and times are stored by the computer in a format called a timestamp. However, this isn’t a format in which you would want to see the date. PHP converts dates from your notation into a timestamp that the computer understands and from a timestamp into a format familiar to people. PHP handles dates and times with built-in functions.

technicalstuff.eps The timestamp format is a Unix Timestamp, which is an integer that is the number of seconds from January 1, 1970, 00:00:00 GMT (Greenwich Mean Time) to the time represented by the timestamp. This format makes it easy to calculate the time between two dates — just subtract one timestamp from the other.

Setting local time

With the release of PHP 5.1, PHP added a setting for a default local time zone to php.ini. If you don't set a default time zone, PHP will guess, which sometimes results in GMT. In addition, PHP displays a message advising you to set your local time zone.

To set a default time zone, follow these steps:

1. Open php.ini in a text editor.

2. Scroll down to the section headed [Date].

3. Find the setting date.timezone =.

4. If the line begins with a semicolon (;), remove the semicolon.

5. Add a time zone code after the equal sign.

You can see a list of time zone codes in Appendix H of the PHP online manual at www.php.net/manual/en/timezones.php. For example, you can set your default time zone to Pacific time with the setting:

date.timezone = America/Los_Angeles

If you don't have access to the php.ini file, you can set a default time zone in each script that applies to that script only, as follows:

date_default_timezone_set("timezonecode");

You can see which time zone is currently your default time zone by using this statement:

$def = date_default_timezone_get()

echo $def;

Formatting a date

The function that you will use most often is date, which converts a date or time from the timestamp format into a format that you specify. The general format is

$mydate = date("format",$timestamp);

$timestamp is a variable with a timestamp stored in it. This code assumes that you previously stored the timestamp in the variable, which you might do using a PHP function (as we'll describe later in this section). If $timestamp isn't included, the current time is obtained from the operating system and used. Thus, you can get today's date with the following:

$today = date("Y/m/d");

If today is August 10, 2013, this statements returns

2013/08/10

The format is a string that specifies the date format that you want stored in the variable. For instance, the format "y-m-d" returns 13-08-10, and "M.d.Y" returns Aug.10.2013. Table 1-6 lists some of the symbols that you can use in the format string. (For a complete list of symbols, see the documentation at www.php.net/manual/en/function.date.php.) The parts of the date can be separated by a hyphen (-), a dot (.), a forward slash (/), or a space.

Table 1-6 Date Format Symbols

Symbol

Meaning

Example

F

Month in text, not abbreviated

January

M

Month in text, abbreviated

Jan

m

Month in numbers with leading zeros

02, 12

n

Month in numbers without leading zeros

1, 12

d

Day of the month; two digits with leading zeros

01, 14

j

Day of the month without leading zeros

3, 30

l

Day of the week in text, not abbreviated

Friday

D

Day of the week in text, abbreviated

Fri

w

Day of the week in numbers

From 0 (Sunday) to 6 (Saturday)

Y

Year in four digits

2014

y

Year in two digits

02

g

Hour between 0 and 12 without leading zeros

2, 10

G

Hour between 0 and 24 without leading zeros

2, 15

h

Hour between 0 and 12 with leading zeros

01, 10

H

Hour between 0 and 24 with leading zeros

00, 23

i

Minutes

00, 59

s

Seconds

00, 59

a

am or pm in lowercase

am, pm

A

AM or PM in uppercase

AM, PM

Storing a timestamp in a variable

You can assign a timestamp with the current date and time to a variable with the following statement:

$today = time();

Another way to store a current timestamp is with the statement

$today = strtotime("today");

You can store specific timestamps by using strtotime with various keywords and abbreviations that are similar to English. For instance, you can create a timestamp for January 15, 2014, as follows:

$importantDate = strtotime("January 15 2014");

The strtotime statement recognizes the following words and abbreviations:

check Month names: Twelve month names and abbreviations

check Days of the week: Seven days and some abbreviations

check Time units: year, month, fortnight, week, day, hour, minute, second, am, pm

check Some useful English words: ago, now, last, next, this, tomorrow, yesterday

check Plus and minus: + or -

check All numbers

check Time zones: For example, gmt (Greenwich Mean Time), pdt (Pacific Daylight Time), and akst (Alaska Standard Time)

You can combine the words and abbreviations in a wide variety of ways. The following statements are all valid:

$importantDate = strtotime("tomorrow"); #24 hours from now

$importantDate = strtotime("now + 24 hours");

$importantDate = strtotime("last saturday");

$importantDate = strtotime("8pm + 3 days");

$importantDate = strtotime("2 weeks ago"); # current time

$importantDate = strtotime("next year gmt");

$importantDate = strtotime("this 4am"); # 4 AM today

If you wanted to know how long ago $importantDate was, you could subtract it from $today. For instance:

$timeSpan = $today - $importantDate;

This gives you the number of seconds between the important date and today. Or use the statement

$timeSpan =(($today - $importantDate)/60)/60

to find out the number of hours since the important date.

Understanding PHP Error Messages

PHP tries to be helpful when problems arise. It provides different types of error messages and warnings with as much information as possible. Here we tell you about those different types of error messages and give you some tips for dealing with them. We also tell you how to display or turn off error messages, and how to store error messages in a log file.

Types of PHP error messages

PHP can display five types of messages. Each type of message displays the name of the file where the error was encountered and the line number where PHP encountered the problem. Different error types provide additional information in the error message. The types of messages are

check Parse error: A parse error is a syntax error that PHP finds when it scans the script before executing it.

check Fatal error: PHP has encountered a serious error that stops the execution of the script.

check Warning: PHP sees a problem, but the problem isn’t serious enough to prevent the script from running.

check Notice: PHP sees a condition that might be an error or might be perfectly okay.

check Strict: Strict messages, added in PHP 5, warn about coding standards. You get strict messages when you use language that is poor coding practice or has been replaced by better code.

tip.eps We recommend writing your PHP scripts with an editor that uses line numbers. If your editor doesn't let you specify which line you want to go to, you have to count the lines manually from the top of the file every time that you receive an error message. You can find information about many editors, including descriptions and reviews, at www.php-editors.com.

Understanding parse errors

Before starting to run a script, PHP scans the script for syntax errors. When it encounters an error, it displays a parse error message. A parse error is a fatal error, preventing the script from even starting to run. A parse error looks similar to the following:

Parse error: parse error, error, in c:\test.php on line 6

Often, you receive this error message because you’ve forgotten a semicolon, a parenthesis, or a curly brace. The error displayed provides as much information as possible. For instance, the following might be displayed:

Parse error: parse error, unexpected T_ECHO, expecting ',' or ';', in c:\test.php on line 6

This error means that PHP found an echo statement where it was expecting a comma or a semicolon, which probably means you forgot the semicolon at the end of the preceding line.

T_ECHO is a token. Tokens represent various parts of the PHP language. Some, like T_ECHO or T_IF, are fairly clear. Others are more obscure. See the appendix of tokens in the PHP online manual (www.php.net/manual/en/tokens.php) for a list of parser tokens with their meanings.

Understanding fatal errors

A fatal error message is displayed when PHP encounters a serious error during the execution of the script that prevents the script from continuing to execute. The script stops running and displays a message that contains as much information as possible to help you identify the problem.

One problem that produces a fatal error message is calling a function that doesn’t exist. (Functions are explained in Chapter 2 in this minibook.) If you misspell a function name in your PHP script, you see a fatal error message similar to the following:

Fatal error: Call to undefined function xxx() in C:\Program Files\Apache Group\Apache2\htdocs\PHPandMySQL\info.php on line 10

In this case, PHP can't find a function named xxx that you call on line 10.

warning_bomb.eps We use the term fatal error to differentiate these types of errors from other errors. However, PHP just calls them (confusingly) errors. You won't find the term fatal error in the manual. Also, the keyword needed to display these types of errors is E_ERROR. (We cover this later in the chapter in the Displaying selected messages section.)

Understanding warnings

A warning message displays when the script encounters a problem but the problem isn’t serious enough to prevent the script from running. Warning messages don’t mean that the script can’t run; the script does continue to run. Rather, warning messages tell you that PHP believes that something is probably wrong. You should identify the source of the warning and then decide whether it needs to be fixed. It usually does.

If you attempt to connect to a MySQL database with an invalid username or password, you see the following warning message:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'@'localhost' (using password: YES) in C:\Program Files\Apache Group\Apache2\htdocs\test.php on line 9

The attempt to connect to the database failed, but the script doesn’t stop running. It continues to execute additional PHP statements in the script. However, because the later statement probably depends on the database connection being established, the later statements won’t execute correctly. This statement needs to be corrected. Most statements that produce warning messages need to be fixed.

Understanding notices

A notice is displayed when PHP sees a condition that might be an error or might be perfectly okay. Notices, like warnings, don’t cause the script to stop running. Notices are much less likely than warnings to indicate serious problems. Notices just tell you that you’re doing something unusual and to take a second look at what you’re doing to be sure that you really want to do it.

One common reason why you might receive a notice is that you’re echoing variables that don’t exist. Here’s an example of what you might see in that instance:

Notice:Undefined variable: age in testing.php on line 9

Understanding strict messages

Strict messages warn about coding standards. They point out language that’s poor coding practice or has been replaced by better code. The strict error type was added in PHP 5. Strict messages don’t stop the execution of the script. However, changing your code so that you don’t see any strict messages makes the script more reliable for the future. Some of the language highlighted by strict messages might be removed entirely in the future.

tip.eps Some of the strict messages refer to PHP language features that have been deprecated. Deprecated functions are old functions that have been replaced by newer functions. The deprecated functions are still supported, but will be removed in the future. PHP might add a separate error type E_DEPRECATED to identify these types of errors so that both E_STRICT and E_DEPRECATED messages will identify different types of problems.

Displaying error messages

You can handle error messages in any of the following ways:

check Display some or all error messages on your web pages.

check Don’t display any error messages.

check Suppress a single error message.

You can tell PHP whether to display error messages or which error messages to display with settings in the php.ini file or with PHP statements in your scripts. Settings in php.ini set error handling for all your scripts. Statements in a script set error handling for that script only.

Turning off error messages

Error messages are displayed on your web pages by default.

warning_bomb.eps Displaying error messages on your web pages is a security risk.

You can have error messages turned on when you’re developing your website, so you can fix the errors, but when your web pages are finished and ready for the public to view, you should shut off the error messages.

You can turn off all error messages for all scripts in your website in the php.ini file. Find the following setting:

display_errors = On

Change On to Off.

You can turn off errors in an individual script with the following statements:

ini_set("display_errors","off");

warning_bomb.eps Changing the setting doesn’t change the error in any way; it changes only whether the error message is displayed. A fatal error still stops the script; it just doesn’t display a message on the web page.

One way to handle error messages is to turn them off in php.ini and turn them on in each individual script during development. Then, when the website is ready for public viewing, you can remove the ini_set statements that turn on the error messages.

Displaying selected messages

You can specify which type of error messages you want to display with the following setting in php.ini:

error_reporting =

You use one of several codes to tell PHP which messages to display. Some possible settings are

error_reporting = E_ALL | E_STRICT

error_reporting = 0

error_reporting = E_ALL & ~ E_NOTICE

The first setting displays E_ALL, which is all errors, warnings, and notices except stricts; and E_STRICT, which displays strict messages. The second setting displays no error messages. The third setting displays all error messages except stricts and notices, because the & ~ means "and not."

Other codes that you can use are E_WARNING, which means all warnings, and E_ERROR, which means all fatal runtime errors.

You can also set the type of message to display for an individual script. You can add a statement to a script that sets the error reporting level for that script only. Add the following statement at the beginning of the script:

error_reporting(errorSetting);

For example, to see all errors except stricts, use the following:

error_reporting(E_ALL);

Suppressing a single error message

You can stop the display of a single error message in a PHP statement. In general, this isn’t a good idea. You want to see your error messages and fix the problems. However, occasionally, suppressing a single notice is the simplest method to prevent an unsightly message from displaying on the web page.

You can stop the display of an error message by placing an at sign (@) where you expect the error message to be generated. For example, the @ in the following statement suppresses an error message:

echo @$news1;

If the variable $news1 hasn't been set previously, this statement would produce the following notice:

Notice: Undefined variable: news1 in C:\Program Files\Apache Group\Apache2\htdocs\PHPandMySQL\info.php on line 10

However, the @ in front of the variable name keeps the notice from being displayed. This feature should be used rarely, but it can be useful in a few situations.

Logging error messages

You can store error messages in a log file. This produces a permanent record of the errors, whether or not they displayed on the web page. Logging messages requires two settings:

check log_errors: Set this to On or Off to send errors to a log file.

check error_log: Specify the filename where errors are to be logged.

Logging errors

You can tell PHP to log errors with a setting in php.ini. Find the following setting:

log_errors = Off

Change the setting to On. After you save the changed php.ini file and restart your web server, PHP logs errors to a text file. You can tell PHP where to send the errors with the error_log setting described in the next section. If you don't specify a file with the error_log settings, the error messages are written to the Apache error log, located in the logs subdirectory in the directory where Apache is installed. The error log has the .err file extension.

You can log errors for an individual script by including the following statement at the beginning of the script:

ini_set("log_errors","On");

This statement sets error logging for this script only.

Specifying the log file

You specify the file where PHP logs error messages with a setting in php.ini. Find the setting:

;error_log = filename

Remove the semicolon from the beginning of the line. Replace filename with the path and filename of the file where you want PHP to log error messages, such as:

error_log = "c:\php\logs\errs.log"

The file you specify doesn’t need to exist. If it doesn’t exist, PHP will create it.

After you save the edited php.ini file and restart your web server, error messages are logged in the specified file. Each error message is logged on a separate line, with the date and time at the beginning of the line.

You can specify a log file for an individual script by including the following statement at the beginning of the script:

ini_set("error_log"," c:\php\logs\errs.log ");

This statement sets the log file for this script only.

Adding Comments to Your PHP Script

Comments are notes embedded in the script itself. Adding comments in your scripts that describe their purpose and what they do is essential. It’s important for the lottery factor — that is, if you win the lottery and run off to a life of luxury on the French Riviera, someone else will have to finish the application. Your successor needs to know what your script is supposed to do and how it does its job. Actually, comments benefit you as well. You might need to revise the script next year when the details are long buried in your mind under thoughts of more recent projects.

Use comments liberally. PHP ignores comments; comments are for humans. You can embed comments in your script anywhere as long as you tell PHP that they are comments. The format for comments is

/* comment text

more comment text */

Your comments can be as long or as short as you need. When PHP sees code that indicates the start of a comment (/*), it ignores everything until it sees the code that indicates the end of a comment (*/).

One possible format for comments at the start of each script is as follows:

/* name: catalog.php

* description: Script that displays descriptions of

* products. The descriptions are stored

* in a database. The product descriptions

* are selected from the database based on

* the category the user entered into a form.

* written by: Lola Designer

* created: 2/1/13

* modified: 3/15/13

*/

You should use comments throughout the script to describe what the script does. Comments are particularly important when the script statements are complicated. Use comments such as the following frequently:

/* Get the information from the database */

/* Check whether the customer is over 18 years old */

/* Add shipping charges to the order total */

PHP also has a short comment format. You can specify that a single line is a comment by using the pound sign (#) or two forward slashes (//) in the following manner:

# This is comment line 1

// This is comment line 2

All text from the # or // to the end of the line is a comment. You can also use # or // in the middle of a line to signal the beginning of a comment. PHP will ignore everything from the # or // to the end of the line. This is useful for commenting a particular statement, as in the following example:

$average = $orderTotal/$nItems; // compute average price

Sometimes you want to emphasize a comment. The following format makes a comment very noticeable:

######################################

## Double-Check This Section ##

######################################

PHP comments aren’t included in the HTML code that is sent to the user’s browser. The user does not see these comments.

Use comments as often as necessary in the script to make it clear. However, using too many comments is a mistake. Don’t comment every line or everything you do in the script. If your script is too full of comments, the important comments can get lost in the maze. Use comments to label sections and explain unusual or complicated code — not obvious code.