The PHP Language

When you think about the English language, you think about it in terms of parts of speech. Nouns name things, verbs explain what things do, adjectives describe things, and so on. Programming languages are similar. A programming language is made up of various "parts of speech" as well. In this section, I'm going to explain the parts of speech that make up the PHP languagecomments, variables, conditional statements, and functions.


Like HTML and JavaScript, PHP supports comments. PHP provides two comment stylesone for single-line comments and another for multiple comments. (If you're familiar with comments in the C or Java programming language, you'll notice that PHP's are the same.) First, single-line comments. To start a single-line comment, use // or #. Everything that follows either on a line is treated as a comment. Here are some examples:

// My function starts here. $color = 'red'; // Set the color for text on the page # $color = 'blue'; $color = $old_color; # Sets the color to the old color. // $color = 'red';

The text that precedes // is processed by PHP, so the second line assigns the $color variable. On the third line, I've turned off the assignment by commenting it out. PHP also supports multiple-line comments, which begin with /* and end with */. If you wanted to comment out several lines of code, you could do it like this:

/* $color = 'red'; $count = 55; // Set the number of items on a page. // $count = $count + 1; */

PHP will ignore all the lines inside the comments. Note that you can put the // style comment inside the multiline comment with no ill effects. You cannot, however, nest multiline comments. This is illegal:

/* $color = 'red'; $count = 55; // Set the number of items on a page. /* $count = $count + 1; */ */


The generally accepted style for PHP code is to use // for singleline comments rather than #.


Variables just provide a way for the programmers to assign a name to a piece of data. In PHP, these names are preceded by a dollar sign ($). Therefore, you might store a color in a variable called $color or a date in a variable named $last_published_at. Here's how you assign values to those variables:

$color = "red"; $last_published_at = time();

The first line assigns the value "red" to $color; the second returns the value returned by the built-in PHP function time() to $last_published_at. That function returns a timestamp represented as the number of seconds since what's called the "Unix epoch."

One thing you should notice here is that you don't have to indicate what kind of item you'll be storing in a variable when you declare it. You can put a string in it, as I did when I assigned "red" to $color. You can put a number in it, as I did with $last_published_at. I know that the number is a timestamp, but as far as PHP is concerned, it's just a number. What if I want a date that's formatted to be displayed rather than stored in seconds so that it can be used in calculations? I can use the PHP date() function. Here's an example:

$last_published_at = date("F j, Y, g:i a");

This code formats the current date so that it looks something like "March 18, 2006, 8:47 pm." As you can see, I can change what kind of information is stored in a variable without doing anything special. It just works. The only catch is that you have to keep track of what sort of thing you've stored in a variable when you use it. For more information on how PHP deals with variable types, see

Despite the fact that variables don't have to be declared as being associated with a particular type, PHP does support various data types, including string, integer, and float (for numbers with decimal points). Not all variable types work in all contexts. One data type that requires additional explanation is the array data type.


The variables you've seen so far in this lesson have all been used to store single values. Arrays are data structures that can store multiple values. You can think of them as lists of values, and those values can be strings, numbers, or even other arrays. To declare an array, use the built-in array function:

$colors = array('red', 'green', 'blue');

This declaration creates an array with three elements in it. Each element in an array is numbered, and that number is referred to as the index. For historical reasons, array indexes start at 0, so for the preceding array, the index of red is 0, the index of green is 1, and the index of blue is 2. You can reference an element of an array using its index, like this:

$color = $colors[1];

By the same token, you can assign values to specific elements of an array as well, like this:

$colors[2] = 'purple';

You can also use this method to grow an array, like this:

$colors[3] = 'orange';

What happens if you skip a few elements when you assign an item to an array, as in the following line?

$colors[8] = 'white';

In this case, not only will element 8 be created, but elements 4 through 7 will be created as well. If you want to append an element onto an array, you just leave out the index when you make the assignment, like this:

$colors[] = 'yellow';

In addition to arrays with numeric indexes, PHP also supports associative arrays, which have indexes supplied by the programmer. These are sometimes referred to as dictionaries or as hashes. Here's an example that shows how they are declared:

$state_capitals = array(   'Texas' => 'Austin',   'Louisiana' => 'Baton Rouge',   'North Carolina' => 'Raleigh',   'South Dakota' => 'Pierre' );

When you reference an associative array, you do so using the keys you supplied, as follows:

$capital_of_texas = $state_capitals['Texas'];

To add a new element to an associative array, you just supply the new key and value, like this:

$state_capitals['Pennsy\lvania'] = 'Harrisburg';

If you need to remove an element from an array, just use the built-in unset() function, like this:


The element with the index specified will be removed, and the array will decrease in size by one element as well. The indexes of the elements with larger indexes than the one that was removed will be reduced by one. You can also use unset() to remove elements from associative arrays, like this:


Array indexes can be specified using variables. You just put the variable reference inside the square brackets, like this:

$i = 1; $var = $my_array[$i];

This also works with associative arrays:

$str = 'dog'; $my_pet = $pets[$str];

As you'll see a bit further on, the ability to specify array indexes using variables is a staple of some kinds of loops in PHP.

As you've seen, there's nothing that distinguishes between a variable that's an array and a variable that holds a string or a number. PHP has a built-in function named is_array() that returns true if its argument is an array and false if the argument is anything else. Here's an example:

is_array(array(1, 2, 3));  // returns true is_array('tree'); // returns false

As I mentioned before, it's perfectly acceptable to use arrays as the values in an array. Therefore, the following is a valid array declaration:

$stuff = ('colors' => array('red', 'green', 'blue'),           'numbers' => array('one', 'two', 'three'));

In this case, I have an associative array that has two elements. The values for each of the elements are arrays themselves. I can access this data structure by stacking the references to the array indexes, like this:

$colors = $stuff['colors']; // Returns the list of colors. $color = $stuff['colors'][1]; // Returns 'green' $number = $stuff['numbers'][0]; // Returns 'one'


The most common data type you'll work with in PHP is the string type. A string is just a series of characters. An entire web page is a string, as is a single letter. To define a string, just place the characters in the string within quotation marks. Here are some examples of strings:

"one" "1" "I like publishing Web pages." "This string spans multiple lines."

Take a look at the last string in the list. The opening quotation mark is on the first line, and the closing quotation mark is on the second line. In PHP, this is completely valid. In some programming languages, strings that span multiple lines are illegalnot so in PHP, where strings can span as many lines as you like, as long as you don't accidentally close the quotation marks.

There's more to strings than just defining them. You can use the . operator to join strings, like this:

$html_paragraph = "<p>" . $paragraph . "</p>";

The $html_paragraph variable will contain the contents of $paragraph surrounded by the opening and closing paragraph tag. The . operator is generally referred to as the string concatenation operator.

Up to this point, you might have noticed that sometimes I've enclosed strings in double quotation marks, and that other times I've used single quotation marks. They both work for defining strings, but there's a difference between the two. When you use double quotation marks, PHP scans the contents of the string for variable substitutions and for special characters. When you use single quotation marks, PHP just uses whatever is in the string without checking to see whether it needs to process the contents.

Special characters are introduced with a backslash, and they are a substitute for characters that might otherwise be hard to include in a string. For example, \n is the substitute for a newline, and \r is the substitute for a carriage return. If you want to include a newline in a string and keep it all on one line, just write it like this:

$multiline_string = "Line one\nLine two";

Here's what I mean by variable substitutions. In a double-quoted string, I can include a reference to a variable inside the string, and PHP will replace it with the contents of the variable when the string is printed, assigned to another variable, or otherwise used. In other words, I could have written the preceding string-joining example as follows:

$html_paragraph = "<p>$paragraph</p>";

PHP will find the reference to $paragraph within the string and substitute its contents. On the other hand, the literal value "$paragraph" would be included in the string if I wrote that line like this:

$html_paragraph = '<p>$paragraph</p>';

You need to do a bit of extra work to include array values in a string. For example, this won't work:

$html_paragraph = "<p>$paragraph['intro']</p>";

You can include the array value using string concatenation:

$html_paragraph = "<p>" . $paragraph['intro'] . "</p>";

You can also use array references within strings if you enclose them within curly braces, like this:

$html_paragraph = "<p>{$paragraph['intro']}</p>";

One final note on defining strings is escaping. As you know, quotation marks are commonly used in HTML as well as in PHP, especially when it comes to defining attributes in tags. There are two ways to use quotation marks within strings in PHP. The first is to use the opposite quotation marks to define the string that you're using within another string. Here's an example:

$tag = '<p >';

I can use the double quotes within the string because I defined it using single quotes. This particular definition won't work, though, if I want to specify the class using a variable. If that's the case, I have two other options:

$tag = "<p class=\"$class\">"; $tag = '<p >';

In the first option, I use the backslash character to "escape" the double quotes that occur within the string. The backslash indicates that the character that follows is part of the string and does not terminate it. The other option is to use single quotes and use the string concatenation operator to include the value of $class in the string.

Conditional Statements

Conditional statements and loops are the bones of any programming language. PHP is no different. The basic conditional statement in PHP is the if statement. Here's how it works:

if ($var == 0) {   echo "Variable set to 0."; }

The code inside the brackets will be executed if the expression in the if statement is true. In this case, if $var is set to anything other than 0, then the code inside the brackets will not be executed. PHP also supports else blocks, which are executed if the expression in the if statement is false. They look like this:

if ($var == 0) {   echo "Variable set to 0."; } else {   echo "Variable set to something other than 0."; }

When you add an else block to a conditional statement, it means that the statement will always do something. If the expression is true, it will run the code in the if portion of the statement. If the expression is not true, it will run the code in the else portion. Finally, there's elseif:

if ($var == 0) {   echo "Variable set to 0."; } elseif ($var == 1) {   echo "Variable set to 1."; } elseif ($var == 2) {   echo "Variable set to 2."; } else {   echo "Variable set to something other than 0, 1, or 2."; }

As you can see, elseif allows you to add more conditions to an if statement. In this case, I added two elseif conditions. There's no limit on elseif conditionsyou can use as many as you need. Ultimately, elseif and else are both conveniences that enable you to write less code to handle conditional tasks.

PHP Conditional Operators

It's hard to write conditional statements if you don't know how to write a boolean expression. First of all, boolean means that an expression (which you can think of as a statement of fact) is either true or false. Here are some examples:

1 == 2 // false 'cat' == 'dog' // false 5.5 == 5.5 // true 5 > 0 // true 5 >= 5 // true 5 < 10 // true

PHP also supports logical operators, such as "not" (which is represented by an exclamation point), "and" (&&), and "or" (||). You can use them to create expressions that are made up of multiple individual expressions, like these:

1 == 1 && 2 == 4 // false 'blue' == 'green' || 'blue' == 'red' // false !(1 == 2) // true, because the ! implies "not" !(1 == 1 || 1 == 2) // false, because ! negates the expression inside the ()

Furthermore, individual values also evaluate to true or false on their own. Any variable set to anything other than 0 or an empty string ("" or '') will evaluate as true, including an array with no elements in it. So if $var is set to 1, the following condition will evaluate as true:

if ($var) {   echo "True."; }

If you want to test whether an array is empty, use the built-in function empty(). So if $var is an empty array, empty($var) will return true. Here's an example:

if (empty($var)) {   echo "The array is empty."; }

You can find a full list of PHP operators at

Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day
Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day (5th Edition)
ISBN: 0672328860
EAN: 2147483647
Year: 2007
Pages: 305

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: