ptg As you’ll see a bit further on, the ability to specify array indexes using variables is a sta- ple of some kinds of loops in PHP. As you’ve seen, nothing 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 To determine whether a particular index is used in an array, you can use PHP’s array_key_exists()function. This function is often used to do a bit of checking before referring to a particular index, for example: if (array_key_exists($state_capitals, “Michigan”)) { echo $state_capitals[“Michigan”]; } As mentioned previously, 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’ Strings 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.” 626 LESSON 21: Taking Advantage of the Server Download from www.wowebook.com ptg 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 illegal—not so in PHP, where strings can span as many lines as you like, so 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 quo- tation marks, PHP scans the contents of the string for variable substitutions and for spe- cial 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 charac- ters 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 new- line 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>”; The PHP Language 627 21 Download from www.wowebook.com ptg 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 com- monly 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 class=”important”>’; 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 vari- able. If that’s the case, I have two other options: $tag = “<p class=\”$class\”>”; $tag = ‘<p class=”’ . $class . ‘“>’; 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, 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 { 628 LESSON 21: Taking Advantage of the Server Download from www.wowebook.com ptg 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 conditions—you 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 exclama- tion 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 () The PHP Language 629 21 Download from www.wowebook.com ptg 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 evalu- ate 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 http://www.php.net/manual/en/language.oper- ators.php. Loops PHP supports several types of loops, some of which are generally more commonly used than others. As you know from the JavaScript lesson, loops execute code repeatedly until a condition of some kind is satisfied. PHP supports several types of loops: do while, while, for, and foreach. I discuss them in reverse order. foreach Loops The foreach loop was created for one purpose—to enable you to process all the ele- ments in an array quickly and easily. The body of the loop is executed once for each item in an array, which is made available to the body of the loop as a variable specified in the loop statement. Here’s how it works: $colors = array(‘red’, ‘green’, ‘blue’); foreach ($colors as $color) { echo $color . “\n”; } This loop prints each of the elements in the $colors array with a linefeed after each color. The important part of the example is the foreach statement. It specifies that the array to iterate over is $colors, and that each element should be copied to the variable $color so that it can be accessed in the body of the loop. 630 LESSON 21: Taking Advantage of the Server Download from www.wowebook.com ptg The foreach loop can also process both the keys and values in an associative array if you use slightly different syntax. Here’s an example: $synonyms = array(‘large’ => ‘big’, ‘loud’ => ‘noisy’, ‘fast’ => ‘rapid’); foreach ($synonyms as $key => $value) { echo “$key is a synonym for $value.\n”; } As you can see, the foreach loop reuses the same syntax that’s used to create associative arrays. for Loops Use for loops when you want to run a loop a specific number of times. The loop state- ment has three parts: a variable assignment for the loop’s counter, an expression (con- taining the index variable) that specifies when the loop should stop running, and an expression that increments the loop counter. Here’s a typical for loop: for ($i = 1; $i <= 10; $i++) { echo “Loop executed $i times.\n”; } $i is the counter (or index variable) for the loop. The loop is executed until $i is larger than 10 (meaning that it will run 10 times). The last expression, $i++, adds one to $i every time the loop executes. The for loop can also be used to process an array instead of foreach if you prefer. You just have to reference the array in the loop statement, like this: $colors = array(‘red’, ‘green’, ‘blue’); for ($i = 0; $i < count(array); $i++) { echo “Currently processing “ . $colors[$i] . “.\n”; } There are a couple of differences between this loop and the previous one. In this case, I start the index variable at 0, and use < rather than <= as the termination condition for the loop. That’s because count() returns the size of the $colors array, which is 3, and loop indexes start with 0 rather than 1. If I start at 0 and terminate the loop when $i is equal to the size of the $colors array, it runs three times, with $i being assigned the values 0, 1, and 2, corresponding to the indexes of the array being processed. Loops 631 21 Download from www.wowebook.com ptg while and do while Loops Both for and foreach are generally used when you want a loop to iterate a specific number of times. The while and do while loops, on the other hand, are designed to be run an arbitrary number of times. Both loop statements use a single condition to deter- mine whether the loop should continue running. Here’s an example with while: $number = 1; while ($number != 5) { $number = rand(1, 10); echo “Your number is $number.\n”; } This loop runs until $number is equal to 5. Every time the loop runs, $number is assigned a random value between 1 and 10. When the random number generator returns a 5, the while loop will stop running. A do while loop is basically the same, except the condi- tion appears at the bottom of the loop. Here’s what it looks like: $number = 1; do { echo “Your number is $number.\n”; $number = rand(1, 10); } while ($number != 5); Generally speaking, the only time it makes sense to use do … while is when you want to be sure the body of the loop will execute at least once. Controlling Loop Execution Sometimes you want to alter the execution of a loop. Sometimes you need to stop run- ning the loop immediately, and other times you might want to just skip ahead to the next iteration of the loop. Fortunately, PHP offers statements that do both. The break state- ment is used to immediately stop executing a loop and move on to the code that follows it. The continue statement stops the current iteration of the loop and goes straight to the loop condition. Here’s an example of how break is used: $colors = (‘red’, ‘green’, ‘blue’); $looking_for = ‘red’; foreach ($colors as $color) { if ($color = $looking_for) { echo “Found $color.\n”; break; } } 632 LESSON 21: Taking Advantage of the Server Download from www.wowebook.com ptg In this example, I’m searching for a particular color. When the foreach loop gets to the array element that matches the color I’m looking for, I print the color out and use the break statement to stop the loop. When I’ve found the element I’m looking for, there’s no reason to continue. I could accomplish the same thing a different way using continue, like this: $colors = (‘red’, ‘green’, ‘blue’); $looking_for = ‘red’; foreach ($colors as $color) { if ($color != $looking_for) { continue; } echo “Found $color.\n”; } In this case, if the color is not the one I’m looking for, the continue statement stops exe- cuting the body of the loop and goes back to the loop condition. If the color is the one I’m looking for, the continue statement is not executed and the echo function goes ahead and prints the color name I’m looking for. The loops I’m using as examples don’t have a whole lot of work to do. Adding in the break and continue statements doesn’t make my programs much more efficient. Suppose, however, that each iteration of my loop searches a very large file or fetches some data from a remote server. If I can save some of that work using break and con- tinue, it could make my script much faster. Built-in Functions PHP supports literally hundreds of built-in functions. You’ve already seen a few, such as echo() and count(). There are many, many more. PHP has functions for formatting strings, searching strings, connecting to many types of databases, reading and writing files, dealing with dates and times, and just about everything in between. You learned that most of the functionality in the JavaScript language is built using the methods of a few standard objects such as window and document. PHP is different— rather than its built-in functions being organized via association with objects, they are all just part of the language’s vocabulary. If you ever get the feeling that there might be a built-in function to take care of some task, check the PHP manual to see whether such a function already exists. Chances are it does. Definitely check whether your function will manipulate strings or arrays. PHP has a huge library of array- and string-manipulation functions that take care of most common tasks. Loops 633 21 Download from www.wowebook.com ptg User-Defined Functions PHP enables you to create user-defined functions that, like JavaScript functions, enable you to package up code you want to reuse. Here’s how a function is declared: function myFunction($arg = 0) { // Do stuff } The function keyword indicates that you’re creating a user-defined function. The name of the function follows. In this case, it’s myFunction. The rules for function names and variable names are the same—numbers, letters, and underscores are valid. The list of arguments that the function accepts follows the function name, in parentheses. The preceding function has one argument, $arg. In this example, I’ve set a default value for the argument. The variable $arg would be set to 0 if the function were called like this: myFunction(); On the other hand, $arg would be set to 55 if the function were called like this: myFunction(55); Functions can just as easily accept multiple arguments: function myOtherFunction($arg1, $arg2, $arg3) { // Do stuff } As you can see, myOtherFunction accepts three arguments, one of which is an array. Valid calls to this function include the following: myOtherFunction(‘one’, ‘two’, array(‘three’)); myOtherFunction(‘one’, ‘two’); myOtherFunction(0, 0, @stuff); myOtherFunction(1, ‘blue’); One thing you can’t do is leave out arguments in the middle of a list. So if you have a function that accepts three arguments, there’s no way to set just the first and third argu- ments and leave out the second, or set the second and third and leave out the first. If you pass one argument in, it will be assigned to the function’s first argument. If you pass in two arguments, they will be assigned to the first and second arguments to the function. 634 LESSON 21: Taking Advantage of the Server Download from www.wowebook.com ptg Returning Values Optionally, your function can return a value, or more specifically, a variable. Here’s a simple example of a function: function add($a = 0, $b = 0) { return $a + $b; } The return keyword is used to indicate that the value of a variable should be returned to the caller of a function. You could call the previous function like this: $sum = add(2, 3); // $sum set to 5 A function can just as easily return an array. Here’s an example: function makeArray($a, $b) { return array($a, $b); } $new_array = makeArray(‘one’, ‘two’); If you don’t explicitly return a value from your function, PHP will return the result of the last expression inside the function anyway. For example, suppose I wrote the add func- tion like this: function add($a = 0, $b = 0) { $a + $b; } Because $a + $b is the last expression in the function, PHP will go ahead and return its result. That’s the case for logical expressions, too. Here’s an example: function negate($a) { !$a; } negate(1); // returns false negate(0); // returns true Your function can also return the result of another function, whether it’s built in or one you wrote yourself. Here are a couple of examples: function add($a = 0, $b = 0) { return $a + $b; } User-Defined Functions 635 21 Download from www.wowebook.com . ‘blue’ == ‘red’ // false ! (1 == 2) // true, because the ! implies “not” ! (1 == 1 || 1 == 2) // false, because ! negates the expression inside the () The PHP Language 629 21 Download from www.wowebook.com ptg Furthermore,. of array- and string-manipulation functions that take care of most common tasks. Loops 633 21 Download from www.wowebook.com ptg User-Defined Functions PHP enables you to create user-defined. use a single condition to deter- mine whether the loop should continue running. Here’s an example with while: $number = 1; while ($number != 5) { $number = rand (1, 10 ); echo “Your number is $number.
”; } This