Introduction to PHP

 < Day Day Up > 

In terms of the way it looks, PHP is a cross between Java and Perl, having taken the best aspects of both and merged them successfully into one language. The Java parts include a powerful object-orientation system, the capability to throw program exceptions, and the general style of writing that both languages borrowed from C. Borrowed from Perl is the "it should just work" mentality where ease of use is favored over strictness. As a result, you will find a lot of "there is more than one way to do it" in PHP.

If you have no previous experience using PHP, these next five sections are just for you: how to start and stop PHP processing, use variables, run operations, control program flow, and work with multiple files. If you have more experience, you can skip to the section "Basic Functions."

Entering and Exiting PHP Mode

Unlike PHP's predecessors, you embed your PHP code inside your HTML as opposed to the other way around. Before PHP, many websites had standard HTML pages for most of their content, linking to Perl CGI pages to do back-end processing when needed. With PHP, all your pages are capable of processing and containing HTML.

Each .php file is processed by PHP that looks for code to execute. PHP considers all the text it finds to be HTML until it finds one of four things:

  • <?php

  • <?

  • <%

  • <script language="php">

The first option is the preferred method of entering PHP mode because it is guaranteed to work. The second method, known as short tags, is disabled by default and is also likely to cause problems if you are serving XML documents along with your PHP. The third option is known as ASP tags because it mimics the manner in which Microsoft's ASP enters code blocks this is rarely used. The last option is a last resort if you are using oddball code generators that don't like <?php it looks like the same script blocks that are used to encapsulate JavaScript, and most editors leave it alone.

You can enter and exit PHP mode whenever you like, as often as you like, and contrary to popular belief there is little speed difference between printing your HTML in HTML mode or printing it in PHP mode.

Once in PHP mode, you can exit it by using ?> (for <?php and <?); %> for <%) or </script> (for <script language="php">). This code example demonstrates entering and exiting PHP mode:

 In HTML mode <?php     echo "In PHP mode"; ?> In HTML mode In <?php echo "PHP"; ?> mode 

Variables

All variables in PHP start with a dollar sign ($). Unlike many other languages, PHP does not have different types of variable for integers, floating-point numbers, arrays, or Booleans. They all start with a $, and all are interchangeable. As a result, PHP is a weakly typed language, which means you do not declare a variable as containing a specific type of data; you just use it however you want to.

This is best explained with some PHP code, so let's take a look at the most basic way of running PHP scripts: through your console. Save the code in Listing 31.1 into the script fedora1.php.

Listing 31.1. Testing Types in PHP
 <?php   $i = 10;   $j = "10";   $k = "Hello, world";   echo $i + $j;   echo $i + $k; ?> 

To run that script, bring up a console and browse to where you saved it. Then type this command:

 $ php fedora1.php 

If PHP is installed correctly, you should see the output 2010, which is really two things. The 20 is the result of 10 + 10 ($i plus $j), and the 10 is the result of adding 10 to the text string Hello, world. Neither of those operations are really straightforward. Whereas $i is set to the number 10, $j is actually set to be the text value "10", which is not the same thing. Adding 10 to 10 gives 20, as you would imagine, but adding 10 to "10" (the string) forces PHP to convert $j to an integer on-the-fly before adding it.

Running $i + $k adds another string to a number, but this time the string is Hello, world and not just a number inside a string. PHP still tries to convert it, though, and converting any non-numeric string into a number converts it to 0. So, the second echo statement ends up saying $i + 0.

As you should have guessed by now, calling echo outputs values to the screen. Right now, that prints directly to your console, but internally PHP has a complex output mechanism that allows you to print to a console, send text through Apache to a web browser, send data over a network, and more.

Now that you have seen how PHP handles variables of different types, it is important that you understand the selection of types available to you:

Type

Stores

integer

Whole numbers; for example, 1, 9, or 324809873

float

Fractional numbers; for example, 1.1, 9.09, or 3.141592654

string

Characters; for example, "a", "sfdgh", or "Fedora Core Unleashed"

boolean

True or false

array

Several variables of any type

object

An instance of a class

resource

Any external data


The first four can be thought of as simple variables, and the last three as complex variables. Arrays are simply collections of variables. You might have an array of numbers (the ages of all the children in a class); an array of strings (the names of all Wimbledon tennis champions); or even an array of arrays, known as a multidimensional array. Arrays are covered in more depth in the next section because they are unique in the way in which they are defined.

Objects also have a section to themselves later in this chapter, but, briefly, they are used to define and manipulate a set of variables that belong to a unique entity. Each object has its own personal set of variables, as well as functions that operate on those variables. Objects are commonly used to model real-world things. You might define an object that represents a TV, with variables like $CurrentChannel (probably an integer), $SupportsHiDef (a Boolean), and so on. Don't worry if this does not make sense right now; objects are complex beasts, which is why they were grouped as complex variables!

Of all the complex variables, the easiest to grasp are resources. PHP has many extensions available to it that allow you to connect to databases, manipulate graphics, or even make calls to Java programs. Because they are all external systems, they need to have types of data unique to them that PHP cannot represent using any of the six other data types. So, PHP stores their custom data types in resources data types that are meaningless to PHP but can be used by the external libraries that created them.

Arrays

Arrays are one of our favorite parts of PHP because the syntax is smart and easy to read and yet manages to be as powerful as you could want. There are four pieces of jargon you need to know to understand arrays:

  • An array is made up of many elements.

  • Each element has a key that defines its place in the array. An array can have only one element with a given key.

  • Each element also has a value, which is the data associated with the key.

  • Each array has a cursor, which points to the current key.

The first three are used regularly; the last one less so. The array cursor is covered later in this chapter in the section "Basic Functions," but we will look at the other three now. With PHP, your keys can be virtually anything: integers, strings, objects, or other arrays. You can even mix and match the keys so that one key is an array, another is a string, and so on. The one exception to all this is floating-point numbers: You cannot use floating-point numbers as keys in your arrays.

There are two ways of adding values to an array: with the [] operator, which is unique to arrays, and with the array() pseudo-function. You should use [] when you want to add items to an existing array and use array() to create a new array.

To sum all this up in code, Listing 31.2 shows a script that creates an array without specifying keys, adds various items to it both without keys and with keys of varying types, does a bit of printing, and then clears the array.

Listing 31.2. Manipulating Arrays
 <?php   $myarr = array(1, 2, 3, 4);   $myarr[4] = "Hello";   $myarr[] = "World!";   $myarr["elephant"] = "Wombat";   $myarr["foo"] = array(5, 6, 7, 8);   echo $myarr[2];   echo $myarr["elephant"];   echo $myarr["foo"][1];   $myarr = array(); ?> 

The initial array is created with four elements, to which we assign the values 1, 2, 3, and 4. Because no keys are specified, PHP automatically assigns keys for us starting at 0 and counting upward giving keys 0, 1, 2, and 3. Then we add a new element with the [] operator, specifying 4 as the key and "Hello" as the value. Next, [] is used again to add an element with the value "World!" and no key and then again to add an element with the key "elephant" and the value "wombat". The line after that demonstrates using a string key with an array value an array inside an array (a multidimensional array).

The next three lines demonstrate reading back from an array, first using a numeric key, then using a string key, and then using a string key and a numeric key. Remember, the "foo" element is an array in itself, so that third reading line retrieves the array and then prints the second element (arrays start at 0, remember). The last line blanks the array by simply using array() with no parameters, which creates an array with elements and assigns it to $myarr.

The following is an alternative way of using array() that allows you to specify keys along with their values:

 $myarr = array("key1" => "value1", "key2" => "value2", 7 => "foo", 15 => "bar"); 

Which method you choose really depends on whether you want specific keys or want PHP to pick them for you.

Variable Variables

Although variable variables are not used frequently, it is at least important that you understand how they work so you will recognize them when you see them. A variable variable allows you to access the value of another variable indirectly by using its name as a string. That is, if you have a variable called $foo with a value "Hello, world!" and another variable called $bar set to "foo", you can use $$bar (yes, two dollar signs) to refer to "Hello, world!". When it sees two dollar signs, PHP looks at the value of the variable and treats that as the name of another variable; then it uses that value.

You can have as many layers of indirection as you like for example, you could have $$$bar, $$$$$person, and so on. That said, anything past two dollar signs is probably not smart.

Listing 31.3 demonstrates variable variables in action.

Listing 31.3. Variable Variables in Action
 <?php   $name = "Paul";   $indirect1 = "name";   $indirect2 = "indirect1";   echo $name . "\n";   echo $$indirect1 . "\n";   echo $$$indirect2 . "\n"; ?> 

This code prints "Paul" tHRee times.

Constants

As you have seen, variables hold values that can be changed during program flow and can vary. It should come as no surprise, then, that constants hold values that are fixed (constant) throughout the entire program. Constants are useful in compiled languages like C because they allow the compiler to allocate precisely enough memory to store them and there is no waste whatsoever. However, in PHP constants are no more efficient than variables and so are less useful.

However, they are used a great deal in functions that require specific values to be passed in. For example, a popular function is extract(), which takes all the values in an array and places them into variables in their own right. You can choose to change the name of the variables as they are extracted using the second parameter send it a 0 and it overwrites variables with the same names as those being extracted, send it a 1 and it skips variables with the same names, send it 5 and it prefixes variables only if they exist already, and so on. Of course, no one wants to have to remember a lot of numbers for each function, so you can instead use EXTR_OVERWRITE for 0, EXtr_SKIP for 1, EXtr_PREFIX_IF_EXISTS for 5, and so on, which is much easier.

You can create constants of your own by using the define() function. Unlike variables, constants do not start with a dollar sign, which makes the code to define a constant look like this:

 <?php   define("NUM_SQUIRRELS", 10);   define("PLAYER_NAME", "Jim");   define("NUM_SQUIRRELS_2", NUM_SQUIRRELS);   echo NUM_SQUIRRELS_2; ?> 

That script demonstrates how you can set constants to numbers, strings, or even the value of other constants, although that doesn't really get used much!

References

Using the equal sign (=) copies the value from one variable to another so they both have their own copy of the value. Another option here is to use references, which is where a variable does not have a value of its own; instead, it points to another variable. This enables you to share values and have variables mutually update themselves.

To copy by reference, use the & symbol, like this:

 <?php   $a = 10;   $b = &$a;   echo $a . "\n";   echo $b . "\n";   $a = 20;   echo $a . "\n";   echo $b . "\n";   $b = 30;   echo $a . "\n";   echo $b . "\n"; ?> 

If you run that script, you will see that updating $a also updates $b, but also that updating $b updates $a, too.

Comments

Although most people believe their code is so beautiful and easy to read that they do not need to write documentation, adding short comments to your code is recommended and usually a requirement in larger software houses. In PHP you have three options for commenting style: //, /* */, and #. The first option (two slashes) instructs PHP to ignore everything until the end of the line. The second (a slash and an asterisk) instructs PHP to ignore everything until it reaches */. The last (a hash symbol) works like // and is included because it is common amongst shell scripting languages.

This code example demonstrates the difference between // and /* */:

 <?php   echo "This is printed!";   // echo "This is not printed";   echo "This is printed!";   /* echo "This is not printed";   echo "This is not printed either"; */ ?> 

It is generally preferred to use // because it is a known quantity. On the other hand, it is easy to introduce coding errors with /* */ by losing track of where a comment starts and ends.

NOTE

Contrary to popular belief, having comments in your PHP script has almost no effect on the speed at which the script executes. What little speed difference exists is wholly removed if you use a code cache.


Escape Sequences

Some characters cannot be typed, and yet you will almost certainly want to use some of them from time to time. For example, you might want to use an ASCII character for new line, but you can't type it. Instead, you need to use an escape sequence: \n. Similarly, you can print a carriage return character with \r. It's important to know both of these because, on the Windows platform, you need to use \r\n to get a new line. If you do not plan to run your scripts anywhere else, you need not worry about this!

Going back to the first script we wrote, you will recall it printed 2010 because we added 10 + 10 and then 10 + 0. We can rewrite that using escape sequences, like this:

 <?php   $i = 10;   $j = "10";   $k = "Hello, world";   echo $i + $j;   echo "\n";   echo $i + $k;   echo "\n"; ?> 

This time PHP prints a new line after each of the numbers, making it obvious that the output is 20 and 10 rather than 2010. Note that the escape sequences must be used in double quotation marks because they will not work in single quotation marks.

Three common escape sequences are \\, which means "ignore the backslash"; \", which means "ignore the double quote"; and \', which means "ignore the single quote." This is important when strings include quotation marks inside them. If we had a string such as "are you really Bill O'Reilly?", which has a single quotation mark in, this code would not work:

 <?php   echo 'Are you really Bill O'Reilly?'; ?> 

PHP would see the opening quotation mark, read all the way up to the O in O'Reilly, and then see the quotation mark following the O as being the end of the string. The Reilly? part would appear to be a fragment of text and would cause an error. You have two options here: You can either surround the string in double quotation marks or escape the single quotation mark with \'.

If you choose the escaping route, it will look like this:

 echo 'Are you really Bill O\'Reilly?'; 

Although they are a clean solution for small text strings, you should be careful with overusing escape sequences. HTML is particularly full of quotation marks, and escaping them can get messy:

 $mystring = "<img src=\"foo.png\" alt=\"My picture\" width=\"100\" height=\"200\" />"; 

In that situation, you are better off using single quotation marks to surround the text simply because it is a great deal easier on the eye!

Variable Substitution

PHP allows you to define strings using three methods: single quotation marks, double quotation marks, or heredoc notation. Heredoc is discussed in the next section because it really does need to be covered by itself, but single quotation marks and double quotation marks work identically, with one minor exception variable substitution.

Consider the following code:

 <?php   $age = 25   echo "You are ";   echo $age; ?> 

That is a particularly clumsy way to print a variable as part of a string. Fortunately, if you put a variable inside a string, PHP performs variable substitution, replacing the variable with its value. That means we can rewrite the code like so:

 <?php   $age = 25   echo "You are $age"; ?> 

The output is the same. The difference between single quotation marks and double quotation marks is that single-quoted strings do not have their variables substituted. Here's an example:

 <?php   $age = 25   echo "You are $age";   echo 'You are $age'; ?> 

The first echo prints "You are 25", but the second one prints "You are $age".

Heredoc Syntax

The third method for setting string variables is called heredoc, and it enables you to use anything you want to signify the start and end of your string. Heredoc uses <<< (tHRee left angle brackets) followed by your string terminator. You can then enclose all the text you want in your string, including variables you want PHP to substitute. When you are done, simply print your terminator at column 0 on a line, followed by a semicolon.

That last part is important: You need to have your heredoc terminator as the first thing on a line by itself. You cannot even have any spaces before the terminator, so be extra careful.

Like many things, this becomes most apparent when you see it in code (see Listing 31.4).

Listing 31.4. Using Heredoc Syntax to Define Strings
 <?php   $variable = "heredoc";   $mystring = <<<EOT   This is some text   This is some more text   This is a $variable substitution EOT;   echo $mystring; ?> 

There are two things to note here. First, the <<<EOT sets up the string "EOT" as the terminator for the heredoc; then that is printed as the first thing on the line to terminate it. We just picked EOT as standing for "end of text," but you can use whatever you like in your own scripts. Second, note there is no \n escape sequence to separate lines because we have physically hard-coded the new line breaks as needed.

Heredoc is generally reserved for situations in which you want to include a large amount of text in your script without having to worry about escaping quotation marks. As long as you ensure you use a heredoc terminator that does not appear in the string itself, you will be fine.

Operators

Now that we have data values to work with, we need some operators to use, too. We have already used + to add variables together, but many others in PHP handle arithmetic, comparison, assignment, and other operators. Operator is just a fancy word for something that performs an operation, like addition or subtraction. However, operand might be new to you. Consider this operation:

 $a = $b + c; 

In this operation, = and + are operators and $a, $b, and $c are operands. Along with +, you will also already know (subtract), * (multiply), and / (divide), but here are some more:

Operator

What It Does

=

Assigns the right operand to the left operand.

==

Returns TRue if the left operand is equal to the right operand.

!=

Returns true if the left operand is not equal to the right operand.

===

Returns true if the left operand is identical to the right operand. This is not the same as ==.

!==

Returns true if the left operand is not identical to the right operand. This is not the same as !=.

<

Returns true if the left operand is smaller than the right operand.

>

Returns TRue if the left operand is greater than the right operand.

<=

Returns TRue if the left operand is equal to or smaller than the right operand.

&&

Returns true if both the left operand and the right operand are true.

||

Returns TRue if either the left operand or the right operand is true.

++

Increments the operand by one.

--

Decrements the operand by one.

+=

Increments the left operand by the right operand.

-=

Decrements the left operand by the right operand.

.

Concatenates the left operand and the right operand (joins them together).

%

Divides the left operand by the right operand and returns the remainder.

|

Performs a bitwise OR operation. It returns a number with bits that are set in either the left operand or the right operand.

&

Performs a bitwise AND operation. It returns a number with bits that are set both in the left operand and the right operand.


There are at least 10 other operators not listed, but to be fair you're unlikely to use them. Even some of the ones in this list are used infrequently bitwise AND, for example. Having said that, the bitwise OR operator is used regularly because it allows you to combine values.

Here is a code example demonstrating some of the operators:

 <?php   $i = 100;   $i++; // $i is now 101   $i--; // $i is now 100 again   $i += 10; // $i is 110   $i = $i / 2; // $i is 55   $j = $i; // both $j and $i are 55   $i = $j % 11; // $i is 0 ?> 

The last line uses modulus, which takes some people a little bit of effort to understand. The result of $i % 11 is 0 because $i is set to 55 and modulus works by dividing the left operand (55) by the right operand (11) and returning the remainder. 55 divides by 11 exactly five times, and so has the remainder 0.

The concatenation operator, a period, sounds scarier than it is: It just joins strings together. For example:

 <?php echo "Hello, " . "world!"; echo "Hello, world!" . "\n"; ?> 

There are two "special" operators in PHP that are not covered here and yet are used frequently. Before we look at them, though, it's important that you see how the comparison operators (such as <, <=, and !=) are used inside conditional statements.

Conditional Statements

In a conditional statement you instruct PHP to take different actions depending on the outcome of a test. For example, you might want PHP to check whether a variable is greater than 10 and, if so, print a message. This is all done with the if statement, which looks like this:

 if (your condition) {   // action to take if condition is true } else {   // optional action to take otherwise } 

The your condition part can be filled with any number of conditions you want PHP to evaluate, and this is where the comparison operators come into their own. For example:

 if ($i > 10) {   echo "11 or higher"; } else {   echo "10 or lower"; } 

PHP looks at the condition and compares $i to 10. If it is greater than 10, it replaces the whole operation with 1; otherwise, it replaces it with 0. So, if $i is 20, the result looks like this:

 if (1) {   echo "11 or higher"; } else {   echo "10 or lower"; } 

In conditional statements, any number other than 0 is considered to be equivalent to the Boolean value true, so if (1) always evaluates to true. There is a similar case for strings if your string has any characters in, it evaluates to true, with empty strings evaluating to false. This is important because you can then use that 1 in another condition through && or || operators. For example, if you want to check whether $i is greater than 10 but less than 40, you could write this:

 if ($i > 10 && $i < 40) {   echo "11 or higher"; } else {   echo "10 or lower"; } 

If we presume that $i is set to 50, the first condition ($i > 10) is replaced with 1 and the second condition ($i < 40) is replaced with 0. Those two numbers are then used by the && operator, which requires both the left and right operands to be true. While 1 is equivalent to true, 0 is not, so the && operand is replaced with 0 and the condition fails.

=, ==, ===, and similar operators are easily confused and often the source of programming errors. The first, a single equal sign, assigns the value of the right operand to the left operand. However, all too often you see code like this:

 if ($i = 10) {   echo "The variable is equal to 10!"; } else {   echo "The variable is not equal to 10"; } 

That is incorrect. Rather than checking whether $i is equal to 10, it assigns 10 to $i and returns TRue. What is needed is ==, which compares two values for equality. In PHP, this is extended so that there is also === (three equal signs), which checks whether two values are identical more than just equal.

The difference is slight but important: If you have a variable with the string value "10" and compare it against the number value of 10, they are equal. Thus, PHP converts the type and checks the numbers. However, they are not identical. To be considered identical, the two variables must be equal (that is, have the same value) and be of the same data type (that is, both are strings, both are integers, and so on).

NOTE

It is common practice to put function calls in conditional statements rather than direct comparisons. For example:

 if (do_something()) { 

If the do_something() function returns true (or something equivalent to true, such as a nonzero number), the conditional statement evaluates to true.


Special Operators

The ternary operator and the execution operator work differently from those we have seen so far. The ternary operator is rarely used in PHP, thankfully, because it is really just a condensed conditional statement. Presumably it arose through someone needing to make his code occupy as little space as possible because it certainly does not make PHP code any easier to read!

The ternary operator works like this:

 $age_description = ($age < 18) ? "child" : "adult"; 

Without explanation, that code is essentially meaningless; however, it expands into the following five lines of code:

 if ($age < 18) {   $age_description = "child"; } else {   $age_description = "adult"; } 

The ternary operator is so named because it has three operands: a condition to check ($age < 18 in the previous code), a result if the condition is true ("child"), and a result if the condition is false ("adult"). Although we hope you never have to use the ternary operator, it is at least important to know how it works in case you stumble across it.

The other special operator is the execution operator, which is the back tick symbol, `. The position of the back tick key varies depending on your keyboard, but it is likely to be just to the left of the 1 key (above Tab). The execution operator executes the program inside the back ticks, returning any text the program outputs. For example:

 <?php   $i = `ls  l`;   echo $i; ?> 

That executes the ls program, passing in l (a lowercase L) to get the long format, and stores all its output in $i. You can make the command as long or as complex as you like, including piping to other programs. You can also use PHP variables inside the command.

Switching

Having multiple if statements in one place is ugly, slow, and prone to errors. Consider the code in Listing 31.5.

Listing 31.5. How Multiple Conditional Statements Lead to Ugly Code
 <?php   $cat_age = 3;   if ($cat_age == 1) {     echo "Cat age is 1";   } else {     if ($cat_age == 2) {       echo "Cat age is 2";     } else {       if ($cat_age == 3) {         echo "Cat age is 3";       } else {         if ($cat_age == 4) {           echo "Cat age is 4";         } else {           echo "Cat age is unknown";         }       }     }   } ?> 

Even though it certainly works, it is a poor solution to the problem. Much better is a switch/case block, which transforms the previous code into what's shown in Listing 31.6.

Listing 31.6. Using a switch/case Block
 <?php   $cat_age = 3;   switch ($cat_age) {     case 1:       echo "Cat age is 1";       break;     case 2:       echo "Cat age is 2";       break;     case 3:       echo "Cat age is 3";       break;     case 4:       echo "Cat age is 4";       break;     default:       echo "Cat age is unknown";   } ?> 

Although it is only slightly shorter, it is a great deal more readable and much easier to maintain. A switch/case group is made up of a switch() statement in which you provide the variable you want to check, followed by numerous case statements. Notice the break statement at the end of each case. Without that, PHP would execute each case statement beneath the one it matches. Calling break causes PHP to exit the switch/case. Notice also that there is a default case at the end that catches everything that has no matching case.

It is important that you do not use case default: but merely default:. Also, it is the last case label, so it has no need for a break statement because PHP exits the switch/case block there anyway.

Loops

PHP has four ways you can execute a block of code multiple times: while, for, foreach, and do...while. Of the four, only do...while sees little use; the others are popular and you will certainly encounter them in other people's scripts.

The most basic loop is the while loop, which executes a block of code for as long as a given condition is true. So, we can write an infinite loop a block of code that continues forever with this PHP:

 <?php   $i = 10;   while ($i >= 10) {     $i += 1;     echo $i;   } ?> 

The loop block checks whether $i is greater or equal to 10 and, if that condition is true, adds 1 to $i and prints it. Then it goes back to the loop condition again. Because $i starts at 10 and we only ever add numbers to it, that loop continues forever. With two small changes, we can make the loop count down from 10 to 0:

 <?php   $i = 10;   while ($i >= 0) {     $i -= 1;     echo $i;   } ?> 

So, this time we check whether $i is greater than or equal to 0 and subtract 1 from it with each loop iteration. while loops are typically used when you are unsure of how many times the code needs to loop because while keeps looping until an external factor stops it.

With a for loop, you specify precise limits on its operation by giving it a declaration, a condition, and an action. That is, you specify one or more variables that should be set when the loop first runs (the declaration), you set the circumstances that will cause the loop to terminate (the condition), and you tell PHP what it should change with each loop iteration (the action). That last part is what really sets a for loop apart from a while loop: You usually tell PHP to change the condition variable with each iteration.

We can rewrite the script that counts down from 10 to 0 using a for loop:

 <?php   for($i = 10; $i >= 0; $i -= 1) {     echo $i;   } ?> 

This time we do not need to specify the initial value for $i outside the loop, and neither do we need to change $i inside the loop it is all part of the for statement. The actual amount of code is really the same, but for this purpose the for loop is arguably tidier and therefore easier to read. With the while loop, the $i variable was declared outside the loop and so was not explicitly attached to the loop.

The third loop type is foreach, which is specifically for arrays and objects, although it is rarely used for anything other than arrays. A foreach loop iterates through each element in an array (or each variable in an object), optionally providing both the key name and the value.

In its simplest form, a foreach loop looks like this:

 <?php   foreach($myarr as $value) {     echo $value;   } ?> 

This loops through the $myarr array we created earlier, placing each value in the $value variable. We can modify that so we get the keys as well as the values from the array, like this:

 <?php   foreach($myarr as $key => $value) {     echo "$key is set to $value\n";   } ?> 

As you can guess, this time the array keys go in $key and the array values go in $value. One important characteristic of the foreach loop is that it goes from the start of the array to the end and then stops and by start we mean the first item to be added rather than the lowest index number. This script shows this behavior:

 <?php   $array = array(6 => "Hello", 4 => "World",                  2 => "Wom", 0 => "Bat");   foreach($array as $key => $value) {     echo "$key is set to $value\n";   } ?> 

If you try this script, you will see that foreach prints the array in the original order of 6, 4, 2, 0 rather than the numerical order of 0, 2, 4, 6.

The do...while loop works like the while loop, with the exception that the condition appears at the end of the code block. This small syntactical difference means a lot, though,. because a do...while loop is always executed at least once. Consider this script:

 <?php   $i = 10;   do {     $i -= 1;     echo $i;   } while ($i < 10); ?> 

Without running the script, what do you think it will do? One possibility is that it will do nothing; $i is set to 10, and the condition states that the code must loop only while $i is less than 10. However, a do...while loop always executes once, so what happens is that $i is set to 10 and PHP enters the loop, decrements $i, prints it, and then checks the condition for the first time. At this point, $i is indeed less than 10, so the code loops, $i is decremented again, the condition is rechecked, $i is decremented again, and so on. This is in fact an infinite loop, and so should be avoided!

If you ever want to exit a loop before it has finished, you can use the same break statement, which we used earlier to exit a switch/case block. This becomes more interesting if you find yourself with nested loops loops inside of loops. This is a common situation to be in. For example, you might want to loop through all the rows in a chessboard and, for each row, loop through each column. Calling break exits only one loop or switch/case, but you can use break 2 to exit two loops or switch/cases, or break 3 to exit three, and so on.

Including Other Files

Unless you are restricting yourself to the simplest programming ventures, you will want to share code amongst your scripts at some point. The most basic need for this is to have a standard header and footer for your website, with only the body content changing. However, you might also find yourself with a small set of custom functions you use frequently, and it would be an incredibly bad move to simply copy and paste the functions into each of the scripts that use them.

PHP gives you two ways to include other files into your current script. Both of them take the full content of the other script and merge it with the current script, allowing you to import functions, variables, or any other settings you have put in place. The basic way to include other files is with the include keyword. Save this script as include1.php:

 <?php   for($i = 10; $i >= 0; $i -= 1) {     include "echo_i.php";   } ?> 

Then save this script as echo_i.php:

 <?php   echo $i; ?> 

If you run include1.php, PHP loops from 10 to 0 and includes echo_i.php each time. For its part, echo_i.php just prints the value of $i, which is a crazy way of performing an otherwise simple operation, but it does demonstrate how included files share data. Note that the include keyword in include1.php is inside a PHP block, but we reopen PHP inside echo_i.php. This is important because PHP exits PHP mode for each new file, so you always have a consistent entry point.

The second way to include files is with the require keyword, which works in the same way as include except that, if PHP cannot find the file you ask for, it terminates execution immediately.

     < Day Day Up > 


    Red Hat Fedora 4 Unleashed
    Red Hat Fedora 4 Unleashed
    ISBN: 0672327929
    EAN: 2147483647
    Year: 2006
    Pages: 361

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net