Tuesday, August 11, 2009

PHP Building Blocks for Programs

HP programs are a series of instructions in a file named with an exten­
sion that tells the Web server to look for PHP sections in the file. (The or , but it can be anything that the Web

extension is usually

.php

server is configured to expect.) PHP begins at the top of the file and executes each instruction, in order, as it comes to it. Instructions are the building blocks of PHP programs.

The basic building blocks are simple statements — a single instruction fol­ lowed by a semicolon. A simple program consists of a series of simple state­ ments. For example, the Hello World program that I discuss in Chapter 6 is a simple program. However, the programs that make up a Web database appli­ cation are not that simple. They are dynamic and interact with both the user and the database. Consequently, the programs require more complex build­ ing blocks.

Here are some common programming tasks that require complex building blocks:

Storing groups of related values together: You often have information that is related, such as the description, picture, and price of a product or a list of customers. Storing this information as a group that you can access under one name is efficient and useful. This PHP feature is an array.

Setting up statements that execute only when certain conditions are met: Programs frequently need to do this. For instance, you may want to display a toy catalog to a child and an electronics catalog to an adult. This type of statement is a conditional statement. The PHP conditional statements are the if statement and the case statement.

Setting up a block of statements that is repeated: You frequently need to repeat statements. For instance, you may want to create a list of all your customers. To do that, you might use two statements: one that gets the customer row from the database and a second one that stores the customer name in a list. You would need to repeat these two statements for every row in the customer database. The feature that enables you to do this is a loop. Three types of loops are for loops, while loops, and do..while loops.

Writing blocks of statements that can be reused many times: Many tasks are performed in more than one part of the application. For instance, you might want to retrieve product information from the data­ base and display it numerous times in an application. Getting and dis­ playing the information might require several statements. Writing a
block of statements that displays the product information and using this block repeatedly is much more efficient than writing the statements over again every time that you need to display the product information. PHP allows you to reuse statement blocks by creating a function.

In this chapter, you find out how to use the building blocks of PHP programs. I describe the most frequently used simple statements and the most useful complex statements and variables. You find out how to construct the building blocks and what they are used for. Then in Chapter 8, you find out how to use these building blocks to move data in and out of a database.

Double quotes and single quotes have different effects on variables. When you use single quotes, variable names are echoed as-is. When you use double quotes, variable names are replaced by the variable values.

You can separate variable names with curly braces ({ }). For instance, the following statements

$pet = “bird”;
echo “The $petcage has arrived.”;

will not output bird as the $pet variable. In other words, the output will not 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 will output

The birdcage has arrived.

echo statements output a line of text that is 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 stages in producing the Web page:

The PHP program: PHP echo statements that you write.

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 statements.

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

The echo statements send exactly what you echo to the browser — no more, no less. If you do not echo any HTML tags, none are sent.

PHP allows some special characters that format output, but they are not HTML tags. The PHP special characters only affect the output from the echo statement — not the display on the Web page. For instance, if you want to start a new line in the PHP output, 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 HTML tag to start a new line on the Web page. Table 7-2 shows examples of the three stages.

Useful Simple Statements

A simple statement is a single instruction followed by a semicolon (;). Here are some useful simple statements used in PHP programs:

echo statement: Produces output that browsers handle as HTML

Assignment statement: Assigns values to variables

Increment statement: Increases or decreases numbers in variables

exit statement: Stops the execution of your program

Function call: Uses stored blocks of statements at any location in a program

I discuss these simple statements and when to use them in the following sections.

Using echo statements

You use echo statements to produce output. The output from an echo state­ ment is sent to the user’s browser, which handles the output as HTML (HyperText Markup Language).

The general format of an echo statement is

echo outputitem,outputitem,outputitem...

where the following rules apply:

An outputitem can be a number, a string, or a variable. A string must be enclosed in quotes. The difference between double and single quotes is explained in Chapter 6.

List as many outputitems as you need.

Separate each outputitem with a comma.

Table 7-1 shows some echo statements and their output. For the purposes of the table, assume that $string1 is set to Hello and $string2 is set to World!.
Table 7-2 summarizes the differences between the stages in creating a Web page with PHP. To look at these differences more closely, consider the follow­ ing two echo statements:

echo “Line 1”;
echo “Line 2”;

If you put these lines in a program, you might expect the Web page to display the following:

Line 1
Line 2

However, this is not the output that you would get. The Web page would actu­
ally 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 output and is sent to the browser contains exactly the characters that you echoed — no more, no less. The character strings that you echoed did not contain any spaces, so no spaces appear between the lines.

Also, notice that the two lines are echoed 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, echo the special character \n. Change the echo statements to the following:

echo “line 1\n”;
echo “line 2”;

Now you get what you want, right? Well, actually no. Now you see the follow­
ing 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 dis­ plays 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:

echo “line 1<br>”;
echo “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

Use \n liberally. Otherwise, your HTML source code will have some really long lines. For instance, if you echo 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. Taking the extra time to add these breaks will pay off if you have to troubleshoot a Web page that doesn’t look the way you expected. It’s much easier to examine the source code if it’s not a mile-long line.

Using assignment statements

Assignment statements are statements that assign values to variables. The variable name is listed to the left of the equal sign; the value to be assigned to the variable is listed to the right of the equal sign. Here is the general format:

$variablename = value;

The value can be a single value or a combination of values, including values in variables. A variable can hold numbers or characters but not both at the same time. Therefore, a value cannot be a combination of numbers and char­ acters. The following are valid assignment statements:

$number = 2;
$number = 2+1;
$number = (2 - 1) * (4 * 5) -17;
$number2 = $number + 3;
$string = “Hello World”;
$string2 = $string.” again!”;

If you combine numbers and strings in a value, you won’t get an error mes­ sage; you’ll just get unexpected results. For instance, the following state­ ments combine numbers and strings:

$number = 2;
$string = “Hello”;
$combined = $number + $string;
$combined2 = $number.$string;
echo $combined;
echo <br>;
echo $combined2;

The output of these statements is

2 ($string is evaluated as 0)
2Hello ($number is evaluated as a character)

Using increment statements

Often a variable is used as a counter. For instance, suppose you want to be sure that everyone sees your company logo, so you display it three times. You set a variable to 0. Each time that you display the logo, you add 1 to the variable. When the value of the variable reaches 3, you know that it’s time to stop showing the logo. The following statements show the use of a counter:

$counter=0;
$counter = $counter + 1;
echo $counter;

These statements would output 1. Because counters are used so often, PHP provides shortcuts. The following statements have the same effect as the pre­ ceding statements.

$counter=0;
$counter++;
echo $counter;

This echo statement also outputs 1 because ++ adds 1 to the current value of
$counter. Or you can use the following statement:

$counter--;

This statement subtracts 1 from the current value of $counter.

Sometimes you may want to do a different arithmetic operation. You can use
any of the following shortcuts:

$counter+=2;
$counter-=3;
$counter*=2;
$counter/=3;

These statements add 2 to $counter, subtract 3 from $counter, multiply
$counter by 2, and divide $counter by 3, respectively.

Using exit

Sometimes you want the program to stop executing — just stop at some point in the middle of the program. For instance, if the program encounters an error, often you want it to stop rather than continue with more state­ ments. The exit statement stops the program. No more statements are exe­ cuted after the exit statement. The format of an exit statement is

exit(“message”);

The message is a message that is output when the program exits. For instance, you might use the statement

exit(“The program is exiting”);

You can also stop the program with the die statement, as follows:

die(“The program is dying”);

The die statement is the same as the exit statement. die is just another name for exit. Sometimes it’s just more fun to say die.

Using function calls

Functions are blocks of statements that perform certain specified tasks. You can think of functions as mini-programs or subprograms. The block of state­ ments is stored under a function name, and you can execute the block of statements any place you want by calling the function by its name. (For details on how to use functions, check out the section, “Using Functions,” later in this chapter.)

You can call a function by listing its name followed by parentheses, like this:

functionname();

For instance, you might have a function that gets all the names of customers that reside in a certain state from the database and displays the names in a list in the format last name, first name. You write the statements that do these tasks and store them as a function under the name get_names. Then when you call the function, you need to specify which state. You can use the following statement at any location in your program to get the list of cus­ tomer names from the given state, which in this case is California:

get_names(‘CA’);

The value in the parentheses is given to the function so it knows which state you’re specifying. This is passing the value. You can pass a list of values.

PHP provides many built-in functions. For example, in Chapter 6, I discuss a built-in function called unset. You can uncreate a variable named $testvar by using this function call:

unset($testvar);

Using PHP Arrays

Arrays are complex variables. An array stores a group of values under a single variable name. An array is useful for storing related values. For instance, you can store information about a shirt (such as size, color, and cost) in a single array named $shirtinfo. Information in an array can be handled, accessed, and modified easily. For instance, PHP has several meth­ ods for sorting an array.

The following few 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 have not referenced $pets at any earlier point in the program, the following statement creates an array called $pets:

$pets[1] = “dragon”;

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

$pets[2] = “unicorn”;
$pets[3] = “tiger”;
Now the array $pets contains three values: dragon, unicorn, and tiger. An array can be viewed as a list of key/value pairs. 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:

$pets[] = “dragon”;
$pets[] = “unicorn”;
$pets[] = “tiger”;

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

echo “$pets[0]”;

sends the following output:

dragon

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:

$pets = array( “dragon”,”unicorn”,”tiger”);

This statement creates the same array as the preceding shortcut. It assigns numbers as keys, starting with 0. 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 that’s enclosed by double quotes, you may need to enclose the array value name in curly braces like this:

echo “The capital of Texas is {$capitals[‘TX’]}<br>”;

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

print_r($capitals);

This print_r statement provides the following output:

Array
(
[CA] => Sacramento
[TX] => Austin
[OR] => Salem
)

This output shows the key and the value for each element in the array.

The output will display on the Web page with HTML, which means that it will display in one long line. To see the output on the Web in the useful format that I 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 a value from an array. For example, suppose you have the following array:

$pets = array( “dragon”, “unicorn”, “tiger”, “parrot”, “scorpion” );

This array has five values. Now you decide that you no longer want to carry scorpions in your pet store, so you use the following statement to try to remove scorpion from the array:

$pets[4] = “”;

Although this statement sets $pets[4] to an empty string, it does not remove it from the array. You still have an array with five values; one of the values is beingemptyl. To totally remove the item from the array, you need to unset it with the following statement:

unset($pets[4]);

Now your array has only four values in it.

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 they were created. Often, you want to change this order. For example, you may 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 statement as follows:

sort($pets);

This statement sorts by the values and assigns new keys that are the appro­ priate numbers. The values are sorted with numbers first, uppercase letters next, and lowercase letters last. For instance, consider the $pets array cre­ ated in the preceding section:

$pets[0] = “dragon”;
$pets[1] = “unicorn”;
$pets[2] = “tiger”;

After the following sort statement

sort($pets);

the array becomes

$pets[0] = “dragon”;
$pets[1] = “tiger”;
$pets[2] = “unicorn”;

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 statement as follows:

asort($capitals);

This statement sorts the capitals by value but keeps the original key for each value instead of assigning a number key. For instance, consider the state capi­ tals array created in the preceding section:

$capitals[‘CA’] = “Sacramento”;
$capitals[‘TX’] = “Austin”;
$capitals[‘OR’] = “Salem”;

After the following sort 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. For example, if the original array were

$capitals[1] = “Sacramento”;
$capitals[2] = “Austin”;
$capitals[3] = “Salem”;

after an asort statement, the new array would be

$capitals[2] = Austin
$capitals[1] = Sacramento
$capitals[3] = Salem

It’s unlikely that you want to use asort on an array with numbers as a key.

There are several other sort statements that sort in other ways. Table 7-3 lists all the available sort statements.

Getting values from arrays

You can retrieve any individual value in an array by accessing it directly. Here is an example:

$CAcapital = $capitals[‘CA’];
echo $CAcapital ;

The output from these statements is

Sacramento

If you use an array element that doesn’t exist in a statement, a notice is dis­ played. (Read about notices in Chapter 6.) 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

Remember that a notice does not cause the script to stop. Statements after the notice will 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 statement gets values from an array and puts them into variables. The following statements include a list statement:

$shirtInfo = array (“large”, “blue”, 12.00); sort ($shirtInfo); list($firstvalue,$secondvalue) = $shirtInfo; echo $firstvalue,”<br>”;
echo $secondvalue,”<br>”;

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

$firstvalue=$shirtInfo[0];
$secondvalue=$shirtInfo[1];

The third value in $shirtInfo is not copied into a variable because there are only two variables in the list statement. The output from the echo state­ ments is

blue large

Notice that the output is in alphabetical order and not in the order in which the values were entered. It’s in alphabetical order because the array is sorted after it is created.

You can retrieve all the values from an array with words as keys using extract. Each value is copied into a variable named for the key. For instance, the fol­ lowing statements get all the information from $shirtInfo and echo it:

extract($shirtInfo);
echo “size is $size; color is $color; cost is $cost”;

The output for these statements is

size is large; color is blue; 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 six to each value in the array. In technical talk, walking through each and every value in an array, in order, is iteration. It is also sometimes called traversing. Here are two ways to walk through an array:

Manually: Move a pointer from one array value to another

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:

current($arrayname): Refers to the value currently under the pointer;
does not move the pointer

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

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

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

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 have moved the pointer previously, the pointer is located at the first element when you start walking through the array. If you think that the array pointer may have been moved earlier in the script or if your output from the array seems to start somewhere in the middle, use the reset state­ ment 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
foreach walks through the array one value at a time and executes the block of statements by using each value in the array. The general format is

foreach( $arrayname as $keyname => $valuename )
{
block of statements;
}

Fill in the following information:

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

keyname: The name of the variable where you want to store the key.
keyname is optional. If you leave out $keyname =>, the value is put into
$valuename.

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.

Multidimensional arrays

In the earlier sections of this chapter, I 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 these prod­ uct prices together in one variable:

shirt, 20.00

pants, 22.50

blanket, 25.00

bedspread, 50.00

lamp, 44.00

rug, 75.00

You can store these products in an array as follows:

$productPrices[‘shirt’] = 20.00;
$productPrices[‘pants’] = 22.50;
$productPrices[‘blanket’] = 25.00;
$productPrices[‘bedspread’] = 50.00;
$productPrices[‘lamp’] = 44.00;
$productPrices[‘rug’] = 75.00;

Your program can easily look through this array whenever it needs to know the price of an item. But suppose that you have 3,000 products. Your program would need to look through 3,000 products to find the one with shirt or rug as the key.

Notice that the list of products and prices includes a wide variety of products that can be classified into groups: clothing, linens, and furniture. If you clas­ sify the products, the program would only need to look through one classifi­ cation to find the correct price. Classifying the products would be much
more efficient. You can classify the products by putting the costs in a multi­
dimensional array as follows:

$productPrices[‘clothing’][‘shirt’] = 20.00;
$productPrices[‘clothing’][‘pants’] = 22.50;
$productPrices[‘linens’][‘blanket’] = 25.00;
$productPrices[‘linens’][‘bedspread’] = 50.00;
$productPrices[‘furniture’][‘lamp’] = 44.00;
$productPrices[‘furniture’][‘rug’] = 75.00;

This kind of array is a multidimensional array because it’s like an array of arrays. Figure 7-1 shows the structure of $productPrices as an array of arrays. The figure shows that $productPrices has three key/value pairs.
The keys are clothing, linens, and furniture. The value for each key is an array with two key/value pairs. For instance, the value for the key clothing is an array with the two key/value pairs: shirt/20.00 and pants/22.50.

$productPrices is a two-dimensional array. PHP can also understand multi­ dimensional arrays that are four, five, six, or more levels deep. However, my head starts to hurt if I try to comprehend an array that is more than three levels deep. The possibility of confusion increases when the number of dimensions increases.

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

$shirtPrice = $productPrices[‘clothing’][‘shirt’];

You can also echo the value:

echo $productPrices[‘clothing’][‘shirt’];

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 “The price of a shirt is \${$productPrices[‘clothing’][‘shirt’]}”;

Notice the backslash (\) in front of the first dollar sign ($). The backslash tells PHP that $ is a literal dollar sign and not the beginning of a variable name. The output is

The price of a shirt is $20

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 nesting.

Because a two-dimensional array, such as $productPrices, 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:

echo “<table border=1>”;
foreach( $productPrices as $category )
{
foreach( $category as $product => $price )
{
$f_price = sprintf(“%01.2f”, $price);
echo “<tr><td>$product:</td><td>\$$f_price</td></tr>”;
}
}
echo “</table>”;

Figure 7-2 shows the Web page produced with these PHP statements.

Here is how the program interprets these statements:

1. Outputs the table tag.

2. Gets the first key/value pair in the $productPrices array and stores the value in the variable $category. The value is an array.

3. Gets the first key/value pair in the $category array. Stores the key in
$product and stores the value in $price.

4. Formats the value in $price into the correct format for money.

5. Echoes one table row for the product and its price.

6. Goes to the next key/value pair in the $category array.

7. Formats the price and echoes the next table row for the product and its price.

8. Because there are no more key/value pairs in $category, the inner
foreach statement ends.

9. Goes to the next key/value pair in the outer foreach statement. Puts the next value in $category, which is an array.

10. Repeats the procedure in Steps 2–9 until the last key/value pair in the last $category array is reached. The inner foreach statement ends. The outer foreach statement ends.

11. Outputs the /table tag to end the table.

In other words, the outer foreach starts with the first key/value pair in the array. The key is clothing, and the value of this pair is an array that is put into the variable $category. The inner foreach then walks through the array in $category. When it reaches the last key/value pair in $category, it ends. The program is then back in the outer loop, which goes on to the second key/value pair . . . and so on until the outer foreach reaches the end of the array.

Useful Conditional Statements

A conditional statement executes a block of statements only when certain con­
ditions are met. Here are two useful types of conditional statements:

if statement: Sets up a condition and tests it. If the condition is true, a block of statements is executed.

switch statement: Sets up a list of alternative conditions. Tests for the true condition and executes the appropriate block of statements.

I describe these statements in more detail in the following two sections.

Using if statements

An if statement asks whether certain conditions exist. A block of statements executes depending on which conditions are met. The general format of an
if conditional statement is

if ( condition ... )
{
block of statements
}
elseif ( condition ... )
{
block of statements
}
else
{
block of statements
}

The if statement consists of three sections:

if: This section is required. It tests a condition.

• If condition is true: The block of statements is executed. After the statements are executed, the program moves to the next instruc­ tion following the conditional statement; if the conditional state­ ment contains any elseif or else sections, the program skips over them.

• If condition is not true: The block of statements is not executed. The program skips to the next instruction, which can be an elseif, an else, or the next instruction after the if conditional statement.

elseif: This section is optional. It tests a condition. You can use more than one elseif section if you want.

• If condition is true: The block of statements is executed. After executing the block of statements, the program goes to the next instruction following the conditional statement; if the if statement contains any additional elseif sections or an else section, the program skips over them.

• If condition is not true: The block of statements is not executed. The program skips to the next instruction, which can be an elseif, an else, or the next instruction after the if conditional statement.

else: This section is optional. Only one else section is allowed. This section does not test a condition; rather, it executes the block of state­ ments. If the program has entered this section, it means that the if sec­ tion and all the elseif sections are not true.

Each section of the if conditional statement tests a condition that consists of one or more comparisons. A comparison asks a question that can be true or false. Some conditions are

$a == 1;
$a < $b
$c != “Hello”

The first comparison asks whether $a is equal to 1; the second comparison asks whether $a is smaller than $b; the third comparison asks whether $c is not equal to “Hello”. You can use two or more comparisons in a condition by connecting the comparisons with and, or, or xor. I discuss comparing
values and using more than one comparison in detail in Chapter 6.The follow­ ing example uses all three sections of the if conditional statement. Suppose that you have German, French, Italian, and English versions of your product catalog. You want your program to display the correct language version, based on where the customer lives. The following statements set a variable
to the correct catalog version (depending on the country where the customer lives) and set a message in the correct language. You can then display a mes­ sage in the appropriate language.

if ($country == “Germany” )
{
$version = “German”;
$message = “ Sie sehen unseren Katalog auf Deutsch”;
}
elseif ($country == “France” )
{
$version = “French”;
$message = “ Vous verrez notre catalogue en francais”;
}
elseif ($country == “Italy” )
{
$version = “Italian”;
$message = “ Vedrete il nostro catalogo in Italiano”;
}
else
{
$version = “English”;
$message = “You will see our catalog in English”;
}
echo “$message<br>”;

The if conditional statement proceeds as follows:

1. Compares the variable $country to “Germany”. If they are the same,
$version is set to “German”, $message is set in German, and the pro­
gram skips to the echo statement. If $country does not equal Germany,
$version and $message are not set, and the program skips to the
elseif section.

2. Compares the variable $country to “France”. If they are the same,
$version and $message are set, and the program skips to the echo statement. If $country does not equal France, $version and $message are not set, and the program skips to the second elseif section.

3. Compares the variable $country to “Italy”. If they are the same,
$version is set to “Italian”, and the program skips to the echo state­ ment. If $country does not equal Italy, $version and $message are not set, and the program skips to the else section.

4. $version is set to English, and $message is set in English. The pro­
gram continues to the echo statement.

Notice that only the message is echoed in this example. However, the vari­ able $version is stored because the version is useful information that can be used later in the program.

When the block to be executed by any section of the if conditional state­ ment contains only one statement, the curly braces are not needed. For instance, if the preceding example only had one statement in the blocks, as follows:

if ($country == “France”)
{
$version = “French”;
}

You could write it as follows:

if ($country == “France” )
$version = “French”;

This shortcut can save some typing, but when several if statements are used, it can lead to confusion.

You can have an if conditional statement inside another if conditional statement. Putting one statement inside another is nesting. For instance, sup­ pose that you need to contact all your customers who live in Idaho. You plan to send e-mail to those who have an e-mail address and send a letter to those who do not have an e-mail address. You can identify the groups of customers by using the following nested if statements:

if ( $custState == “ID” )
{
if ( $EmailAdd != “” )
{
$contactMethod = “letter”;
}
else
{

$contactMethod = “email”;
}
}
else
{
$contactMethod = “none needed”;
}

These statements first check to see whether the customer lives in Idaho. If the customer does live in Idaho, the program tests for an e-mail address. If the e-mail address is blank, the contact method is set to letter. If the e-mail address is not blank, the contact method is email. If the customer does not live in Idaho, the else section sets the contact method to indicate that the customer will not be contacted at all.

Using switch statements

For most situations, the if conditional statement works best. However, sometimes you have a list of conditions and want to execute different state­ ments for each of the conditions. For instance, suppose that your program computes sales tax. How do you handle the different state sales tax rates? The switch statement was designed for such situations.

The switch statement tests the value of one variable and executes the block of statements for the matching value of the variable. The general format is

switch ( $variablename )
{
case value :
block of statements;
break;
case value :
block of statements;
break;
... default:
block of statements;
break;
}

The switch statement tests the value of $variablename. The program then skips to the case section for that value and executes statements until it reaches a break statement or the end of the switch statement. If there is no case section for the value of $variablename, the program executes the default section. You can use as many case sections as you need. The default section is optional. If you use a default section, it’s customary to put the default section at the end, but it can go anywhere.

170 Part III: PHP

The following statements set the sales tax rate for different states:

switch ( $custState )
{
case “OR” :
$salestaxrate = 0;
break;
case “CA” :
$salestaxrate = 1.0;
break;
default:
$salestaxrate = .5;
break;
}
$salestax = $orderTotalCost * $salestaxrate;

In this case, the tax rate for Oregon is 0, the tax rate for California is 100 per­ cent, and the tax rate for all the other states is 50 percent. The switch state­ ment looks at the value of $custState and skips to the section that matches the value. For instance, if $custState is TX, the program executes the default section and sets $salestaxrate to .5. After the switch statement, the program computes $salestax at .5 times the cost of the order.

The break statements are essential in the case section. If a case section does not include a break statement, the program does not stop executing at the end of the case section. The program continues executing statements past the end of the case section, on to the next case section, and continues until it reaches the end of the switch statement (or perhaps a break state­ ment in a later case section).

The last case section in a switch statement doesn’t actually require a break statement. You can leave it out. However, it’s a good idea to include it for clarity.

Using Loops

Loops, which are used frequently in programs, set up a block of statements that repeat. Sometimes, the loop repeats a specified number of times. For instance, a loop to echo all the state capitals needs to repeat 50 times. Sometimes, the loop repeats until a certain condition exists. For instance, a loop that displays product information for all the products needs to repeat until it has displayed all the products, regardless of how many products there are. Here are three types of loops:

Basic for loop: Sets up a counter; repeats a block of statements until the counter reaches a specified number

while loop: Sets up a condition; checks the condition; and if it is true, repeats a block of statements

do..while loop: Sets up a condition; executes a block of statements; checks the condition; if the condition is true, repeats the block of statements

I describe each of these loops in detail in the following few sections.

Using for loops

The most basic for loops are based on a counter. You set the beginning value for the counter, set the ending value, and set how the counter is incremented. The general format is

for (startingvalue;endingcondition;increment)
{
block of statements;
}

Fill in the following values:

startingvalue: A statement that sets up a variable to be your counter and sets it to your starting value. For instance, the statement $i=1; sets
$i as the counter variable and sets it equal to 1. Frequently, the counter variable is started at 0 or 1. The starting value can be a combination of numbers (2 + 2) or a variable.

endingcondition: A statement that sets your ending value. As long as this statement is true, the block of statements keeps repeating. When this statement is not true, the loop ends. For instance, the statement
$i<10; sets the ending value for the loop to 10. When $i is equal to 10, the statement is no longer true (because $i is no longer less than 10), and the loop stops repeating. The statement can include variables, such as $i<$size;.

increment: A statement that increments your counter. For instance, the statement $i++; adds 1 to your counter at the end of each block of statements. You can use other increment statements, such as $I+=1;
or $i--;.

The basic for loop sets up a variable — for example, a variable called $i, — that is a counter. This variable has a value during each loop. The variable $i can be used in the block of statements that is repeating. For instance, the following simple loop displays Hello World! three times:

for ($i=1;$i<=3;$i++)
{
echo “$i. Hello World!<br>”;
}

The statements in the block do not need to be indented. PHP doesn’t care whether they’re indented. However, indenting the blocks makes it much easier for you to understand the program.

The output from these statements is

1. Hello World!
2. Hello World!
3. Hello World!

for loops are particularly useful to loop through an array. Suppose that you have an array of customer names and want to display them all. You can do this easily with a loop:

for ($i=0;$i<100;$i++)
{
echo “$customerNames[$i]<br>”;
}

The output displays a Web page with a list of all the customer names, one on each line. In this case, you know that you have 100 customer names, but sup­ pose that you don’t know how many customers are in this list. You can ask PHP how many values are in the array and use that value in your for loop. For example, you can use the following statements:

for ($i=0;$i<sizeof($customerNames);$i++)
{
echo “$customerNames[$i]<br>”;
}

Advanced for loops
The structure of a for loop is quite flexible and allows you to build loops for almost any purpose. A for loop has this general format:

for ( beginning statements; conditional statements; ending statements)

{

}

Where

block of statements;

The beginning statements execute once at the start of the loop.

The conditional statements are tested for each iteration of the loop.

The ending statements execute once at the end of the loop.

Each of the statement sections is separated by a semicolon (;). Each section can contain as many statements as needed, separated by commas. Any section can be empty.

The following loop has statements in all three sections:

for ($i=0,$j=1;$t<=4;$i++,$j++)
{
$t = $i + $j;
echo “$t<br>”;
}

The output of these statements is

1
3
5

The loop is executed in the following order:

1. The beginning section containing two statements is executed; $i is set to 0, and $j is set to 1.

2. The conditional section containing one statement is evaluated. Is $t less than or equal to 4?
Yes, so the statement is true. The loop continues to execute.

3. The statements in the statement block are executed. $t becomes equal to $i plus $j, which is 0 + 1, which equal 1. Then $t is echoed to give the output 1.

4. The ending section containing two statements is executed — $i++ and $j++. One is added to $i so it equals 1, and 1 is added to $j so that it now equals 2.

5. The conditional section is evaluated. Is $t less than or equal to 4? Because $t is equal to 1 at this point, the statement is true. The loop continues to execute.

6. The statements in the statement block are executed. $t becomes equal to $i plus $j, which is 1 + 2, which equal 3. Then $t is echoed to give the output 3.

7. The ending section containing two statements is executed — $i++ and $j++. One is added to $i so it equals 2, and 1 is added to $j so that it equals 3.

8. The conditional section is evaluated. Is $t less than or equal to 4? Because $t now equals 3, the statement is true. The loop continues to execute.

9. The statements in the statement block are executed. $t becomes equal to $i plus $j, which is 2 + 3, which equal 5. Then $t is echoed to give the output 5.

10. The ending section containing two statements is executed — $i++ and $j++. One is added to $i so it equals 3, and one is added to $j so that it equals 4.

11. The conditional section is evaluated. Is $t less than or equal to 4? Because $t now equals 5, the statement is not true. The loop does not continue to execute. The loop ends, and the pro­ gram continues to the next statement after the end of the loop.

Notice that the ending value is sizeof($customerNames). This statement finds out the number of values in the array and uses that number. That way, your loop repeats exactly the number of times that there are values in the array.

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.

Using while loops

A while loop continues repeating as long as certain conditions are true. The loop works as follows:

1. You set up a condition.

2. The condition is tested at the top of each loop.

3. If the condition is true, the loop repeats. If the condition is not true, the loop stops.

The general format of a while loop is

while ( condition )
{
block of statements
}

A condition is any expression that can be found to be true or false. Comparisons, such as the following, are often used as conditions. (For detailed information on using comparisons, see Chapter 6.)

$test <= 10
$test1 == $test2
$a == “yes” and $b != “yes”
$name != “Smith”

As long as the condition is found to be true, the loop will repeat. When the condition tests false, the loop will stop. The following statements set up a while loop that looks through an array for a customer named Smith:

$customers = array( “Huang”, “Smith”, “Jones” );
$testvar = “no”;
$k = 0;
while ( $testvar != “yes” )
{
if ($customers[$k] == “Smith” )
{
$testvar = “yes”;
echo “Smith<br>”;
}
else
{
echo “$customers[$k], not Smith<br>”;
}
$k++;
}

These statements display the following on a Web page:

Huang, not Smith
Smith

The program executes the previous statements as follows:

1. Sets the variables before starting the loop: $customers (an array with three values), $testvar (a test variable set to “no”), and $k (a counter variable set to 0).

2. Starts the loop by testing whether $testvar != “yes” is true. Because
$testvar was set to “no”, the statement is true, so the loop continues.

3. Tests the if statement. Is $customers[$k] == “Smith” true? At this point, $k is 0, so the program checks $customers[0]. Because
$customers[0] is “Huang”, the statement is not true. The statements in the if block are not executed, so the program skips to the else statement.

4. Executes the statement in the else block. The else block outputs the line “Huang, not Smith”. This is the first line of the output.

5. Adds one to $k, which now becomes equal to 1.

6. Reaches the bottom of the loop.

7. Goes to the top of the loop.

8. Tests the condition again. Is $testvar != “yes” true? Because
$testvar has not been changed and is still set to “no”, it is true,
so the loop continues.

9. Tests the if statement. Is $customers[$k] == “Smith” true? At this point, $k is 1, so the program checks $customers[1]. Because
$customers[1] is “Smith”, the statement is true. So the loop enters the if block.

10. Executes the statements in the if block. Sets $testvar to “yes”. Outputs “Smith”. This is the second line of the output.

11. Adds one to $k which now becomes equal to 2.

12. Reaches the bottom of the loop.

13. Goes to the top of the loop.

14. Tests the condition again. Is $testvar != “yes” true? Because
$testvar has been changed and is now set to “yes”, it is not true. The loop stops.

It’s possible to write a while loop that is infinite — that is, a loop that loops forever. You can easily, without intending to, write a loop in which the condi­ tion is always true. If the condition never becomes false, the loop never ends. For a discussion of infinite loops, see the section “Infinite loops,” later in this chapter.

Using do..while loops

do..while loops are very similar to while loops. A do..while loop contin­ ues repeating as long as certain conditions are true. You set up a condition. The condition is tested at the bottom of each loop. If the condition is true, the loop repeats. When the condition is not true, the loop stops.

The general format for a do..while loop is

do
{
block of statements
} while ( condition );

The following statements set up a loop that looks for the customer named Smith. This program does the same thing as a program in the preceding sec­ tion using a while loop:

$customers = array( “Huang”, “Smith”, “Jones” );
$testvar = “no”;
$k = 0;
do
{
if ($customers[$k] == “Smith” )
{
$testvar = “yes”;
echo “Smith<br>”;
}
else
{
echo “$customers[$k], not Smith<br>”;
}
$k++;
} while ( $testvar != “yes” );

The output of these statements in a browser is

Huang, not Smith
Smith

This is the same output shown for the while loop example. The difference between a while loop and a do..while loop is where the condition is checked. In a while loop, the condition is checked at the top of the loop. Therefore, the loop will never execute if the condition is never true. In the do..while loop, the condition is checked at the bottom of the loop. Therefore, the loop always executes at least once even if the condition is never true.

For instance, in the preceding loop that checks for the name Smith, suppose the original condition is set to yes, instead of no, by using this statement:

$testvar = “yes”;

The condition would test false from the beginning. It would never be true. In a while loop, there would be no output. The statement block would never run. However, in a do..while loop, the statement block would run once before
the condition was tested. Thus, the while loop would produce no output, but the do..while loop would produce the following output:

Huang, not Smith

The do..while loop produces one line of output before the condition is tested. It does not produce the second line of output because the condition tests false.

Infinite loops

You can easily set up loops so that they never stop. These are infinite loops. They repeat forever. However, seldom does anyone create an infinite loop intentionally. It is usually a mistake in the programming. For instance, a slight change to the program that sets up a while loop can make it into an infinite loop.

Here is the program shown in the section, “Using while loops,” earlier in this chapter:

$customers = array ( “Huang”, “Smith”, “Jones” );
$testvar = “no”;
$k = 0;
while ( $testvar != “yes” )
{
if ($customers[$k] == “Smith” )
{

$testvar = “yes”;
echo “Smith<br>”;
}
else
{
echo “$customers[$k], not Smith<br>”;
}
$k++;
}

Here is the program with a slight change:

$customers = array ( “Huang”, “Smith”, “Jones” );
$testvar = “no”;
while ( $testvar != “yes” )
{
$k = 0;
if ($customers[$k] == “Smith” )
{
$testvar = “yes”;
echo “Smith<br>”;
}
else
{
echo “$customers[$k], not Smith<br>”;
}
$k++;
}

The small change is moving the statement $k = 0; from outside the loop to inside the loop. This small change makes it into an endless loop. The output of this changed program is

Huang, not Smith Huang, not Smith Huang, not Smith Huang, not Smith
...

This will repeat forever. Every time the loop runs, it resets $k to 0. Then it gets $customers[0] and echoes it. At the end of the loop, $k is incremented to 1. However, when the loop starts again, $k is set back to 0. Consequently, only the first value in the array, Huang, is ever read. The loop never gets to the name Smith, and $testvar is never set to “yes”. The loop is endless.

Don’t be embarrassed if you write an infinite loop. I guarantee that the best programming guru in the world has written many infinite loops. It’s not a big deal. If you are testing a program and get output in your Web page repeating endlessly, it will stop by itself in a short time. The default time is 30 seconds, but the timeout period may have been changed by the PHP administrator.

You can also click the Stop button on your browser to stop the display in your browser. Then figure out why the loop is repeating endlessly and fix it.

A common mistake that can result in an infinite loop is using a single equal sign (=) when you mean double equal signs (==). The single equal sign stores a value in a variable; the double equal signs test whether two values are equal. If you write the following condition with a single equal sign:

while ($testvar = “yes”)

it is always true. The condition simply sets $testvar equal to “yes”. This is not a question that can be false. What you probably meant to write is this:

while ($testvar == “yes”)

This is a question asking whether $testvar is equal to “yes”, which can be answered either true or false.

You can bulletproof your programs against this particular error by changing the condition to “yes” == $testvar. It’s less logical to read but protects against the single-equals-sign problem. If you use a single equal sign instead of a double equal sign in this condition, you get an error, and your program fails to run.

Another common mistake is to leave out the statement that increments the counter. For instance, in the program earlier in this section, if you leave out the statement $k++;, $k is always 0, and the result is an infinite loop.

Breaking out of a loop

Sometimes you want your program to break out of a loop. PHP provides two statements for this purpose:

break: Breaks completely out of a loop and continues with the program statements after the loop.

continue: Skips to the end of the loop where the condition is tested. If the condition tests positive, the program continues from the top of the loop.

break and continue are usually used in a conditional statement. break, in particular, is used most often in switch statements, as I discuss earlier in the chapter.

The following two sets of statements show the difference between continue
and break. The first statements use the break statement.

$counter = 0;
while ( $counter < 5 )
{
$counter++;
If ( $counter == 3 )
{
echo “break<br>”;
break;
}
echo “End of while loop: counter=$counter<br>”;
}
echo “After the break loop<p>”;

The following statements use the continue statement:

$counter = 0;
while ( $counter < 5 )
{
$counter++;
If ( $counter == 3 )
{
echo “continue<br>”;
continue;
}
echo “End of while loop: counter=$counter<br>”;
}
echo “After the continue loop<br>”;

These statements build two loops that are the same except that the first one uses break, and the second one uses continue. The output from these first statements that use the break statement displays in your browser as follows:

End of while loop: counter=1
End of while loop: counter=2 break
After the break loop

The output from the second group of statements with the continue state­
ment is as follows:

End of while loop: counter=1
End of while loop: counter=2 continue
End of while loop: counter=4
End of while loop: counter=5
After the continue loop

The first loop ends at the break statement. It stops looping and jumps imme­ diately to the statement after the loop. The second loop does not end at the continue statement. It just stops the third repeat of the loop and jumps back up to the top of the loop. It then finishes the loop, with the fourth and fifth repeats, before it goes to the statement after the loop.

One use for break statements is insurance against infinite loops. The follow­
ing statements inside a loop can stop it at a reasonable point:

$test4infinity++;
if ($test4infinity > 100 )
{
break;
}

If you’re sure that your loop should never repeat more than 100 times, these statements will stop the loop if it becomes endless. Use whatever number seems reasonable for the loop that you’re building.

Using Functions

Applications often perform the same task at different points in the program or in different programs. For instance, your application might display the company logo on several different Web pages or in different parts of the pro­ gram. Suppose that you use the following statements to display the company logo:

echo ‘<hr width=”50” align=”left”>’,”\n”;
echo ‘<img src=”/images/logo.jpg” width=”50”
height=”50”><br>’,”\n”;
echo ‘<hr width=”50” align=”left”><br>’,”\n”;

You can create a function that contains the preceding statements and name it display_logo. Then whenever the program needs to display the logo, you can just call the function that contains the statements with a simple function call, as follows:

display_logo();

Notice the parentheses after the function name. These are required in a func­
tion call because they tell PHP that this is a function. Using a function offers several advantages:
Less typing: You only have to type the statements once — in the func­ tion. Forever after, you just use the function call and never have to type the statements again.

Easier to read: The line display_logo() is much easier for a person to understand at a glance.

Fewer errors: After you have written your function and fixed all its prob­
lems, it runs correctly wherever you use it.

Easier to change: If you decide to change how the task is performed, you only need to change it in one place. You just change the function instead of finding a hundred different places in your program where you performed the task and changing the code a hundred times. For instance, suppose that you changed the name of the graphics file that holds the company logo. You just change the filename in one place, the function, and it works correctly everywhere.

You can create a function by putting the code into a function block. The gen­
eral format is

function functionname()
{
block of statements;
return;
}

For instance, you create the function to display the company logo with the following statements:

function display_logo()
{
echo ‘<hr width=”50” align=”left”>’,”\n”;
echo ‘<img src=”/images/logo.jpg” width=”50”
height=”50”><br>’,”\n”;
echo ‘<hr width=”50” align=”left”><br>’,”\n”;
return;
}

The return statement stops the function and returns to the main program. The return statement at the end of the function is not required, but it makes the function easier to understand. The return statement is often used for a conditional end to a function.

Suppose that your function displays an electronics catalog. You might use the following statement at the beginning of the function:

if ( $age < 13 )
return;

If the customer’s age is less than 13, the function stops, and the electronics catalog isn’t displayed.

You can put functions anywhere in the program, but the usual practice is to put all the functions together at the beginning or the end of the program file. Functions that you plan to use in more than one program can be in a separate file. Each program accesses the functions from the external file. For more on organizing applications into files and accessing separate files, check out Chapter 10.

Notice that the sample function is quite simple. It doesn’t use variables, and it doesn’t share any information with the main program. It just performs an independent task when called. You can use variables in functions and pass information between the function and the main program as long as you know the rules and limitations. The remaining sections in this chapter explain how to use variables and pass values.

Using variables in functions

You can create and use variables that are local to the function. That is, you can create and use a variable inside your function. However, the variable is not available outside of the function; it’s not available to the main program. You can make the variable available by using a special statement called global that makes a variable available at any location in the program. For instance, the following function creates a variable:

function format_name()
{
$first_name = “Goliath”;
$last_name = “Smith”;
$name = $last_name.”, “.$first_name;
}
format_name();
echo “$name”;

These statements produce no output. In the echo statement, $name doesn’t contain any value. The variable $name was created inside the function, so it doesn’t exist outside the function.

You can create a variable inside a function that does exist outside the func­ tion by using the global statement. The following statements contain the same function with a global statement added:

function format_name()
{
$first_name = “Goliath”;
$last_name = “Smith”;
global $name;
$name = $last_name.”, “.$first_name;
}
format_name();
echo “$name”;

The program now echoes this:

Smith, Goliath

The global statement makes the variable available at any location in the pro­ gram. You must make the variable global before you can use it. If the global statement follows the $name assignment statement, the program does not produce any output.

The same rules apply when you’re using a variable that was created in the main program. You can’t use a variable in a function that was created outside the function unless the variable is global, as shown in the following statements:

$first_name = “Goliath”;
$last_name = “Smith”;
function format_name()
{
global $first_name, $last_name;
$name = $last_name.”, “.$first_name;
echo “$name”;
}
format_name();

If you don’t use the global statement, $last_name and $first_name inside the function are different variables, created when you name them. They
have no values. The program would produce no output without the global
statement.

Passing values between a function and the main program

You can pass values into the function and receive values from the function. For instance, you might write a function to add the correct sales tax to an order. The function would need to know the cost of the order and which state the customer resides in. The function would need to send back the amount of the sales tax.

Passing values to a function
You can pass values to a function by putting the values between the paren­
theses when you call the function, as follows:

functionname(value,value,...);

Of course, the variables can’t just show up. The function must be expecting them. The function statement includes variable names for the values that it’s expecting, as follows:

function functionname($varname1,$varname2,...)
{
statements return;
}

Chapter 7: PHP Building Blocks for Programs 185

For example, the following function computes the sales tax:

function compute_salestax($amount,$custState)
{
switch ( $custState )
{
case “OR” :
$salestaxrate = 0;
break;
case “CA” :
$salestaxrate = 1.0;
break;
default:
$salestaxrate = .5;
break;
}
$salestax = $amount * $salestaxrate;
echo “$salestax<br>”;
}
$cost = 2000.00;
$custState = “CA”;
compute_salestax($cost,$custState);

The first line shows that the function expects two values, as follows:

function compute_salestax($amount,$custState)

The last line is the function call, which passes two values to the function compute_salestax, as it expects. The amount of the order and the state in which the customer resides are passed. The output from this program is
2000 because the tax rate for California is 100 percent.

You can pass as many values as you need to. Values can be variables or values, including values that are computed. The following function calls are valid:

compute_salestax(2000,”CA”); compute_salestax(2*1000,””); compute_salestax(2000,”C”.”A”);

Values can be passed in an array. The function receives the variable as an array. For instance, the following statements pass an array:

$arrayofnumbers = array( 100, 200);
addnumbers($arrayofnumbers);

The function receives the entire array. For instance, suppose the function starts with the following statement:

function addnumbers($numbers)

The variable $numbers is an array. The function can include statements such as

return $numbers[0] + $numbers[1];

The values passed are passed by position. That is, the first value in the list that you pass is used as the first value in the list that the function expects, the second is used for the second, and so forth. If your values aren’t in the same order, the function uses the wrong value when performing the task. For instance, for compute_salestax, you might call compute_salestax passing values in the wrong order as follows:

compute_salestax($custState,$orderCost);

The function uses the state as the cost of the order, which it sets to 0
because the value passed is a string. It sets the state to the number in
$orderCost, which would not match any of its categories. The output would be 0.

If you do not send enough values, the function sets the missing value to an empty string for a string variable or to 0 for a number. If you send too many values, the function ignores the extra values.

If you pass the wrong number of values to a function, you might get a warning message, as follows, depending on the error message level that PHP is set to.

Warning: Missing argument 2 for compute_salestax() in /test7.php on line 5

For the lowdown on warning messages, check out Chapter 6.

You can set default values to be used when a value isn’t passed. The defaults are set when you write the function by assigning a default value for the value(s) that it is expecting, as follows:

function add_2_numbers($num1=1,$num2=1)
{
$total = $num1 + $num2;
return $total;
}

If one or both values are not passed, the function uses the assigned defaults. But if a value is passed, it is used instead of the default. For example, you could use one of the following calls:

add_2_numbers(2,2); add_2_numbers(2); add_2_numbers();

The results are, in consecutive order:

$total = 4
$total = 3
$total = 2

Getting a value from a function
When you call a function, you can pass values as described above. The func­ tion can also pass a value back to the program that called it. Use the return statement. to pass a value back to the calling program. The program can store the value in a variable or use the value directly, such as using it in a conditional statement. The return statement also returns control to the main program; that is, it stops the function.

The general format of the return statement is

return value;

For instance, in the tax program from the preceding section, I echo the sales tax by using the following statements:

$salestax = $amount * $salestaxrate;
echo “$salestax<br>”;

I could return the sales tax to the main program, rather than echoing it, by using the following statement:

$salestax = $amount * $salestaxrate;
return $salestax;

In fact, I could use a shortcut and send it back to the main program with one statement:

return $amount * $salestaxrate;

The return statement sends the salestax back to the main program and ends the function. The main program can use the value in any of the usual ways. The following statements use the function call in valid ways:

$salestax = compute_salestax($cost,$custState);

$totalcost = $cost + compute_salestax($cost,$custState);

if ( compute_salestax($cost,$custState) > 100000.00 )
$echo “Thank you very, very, very much<br>”;

foreach($customerOrder as $amount)
{
$total = $amount + compute_salestax($amount,$custState);
echo “Your total is $total<br>”;
}

A return statement can return only one value. However, the value returned can be an array, so you can actually return many values from a function.

You can use return statements in a conditional statement to return different values for different conditions. For example, the following function returns one of two different strings:

function compare_values($value1,$value2)
{
if($value1 < $value2)
{
return “less than”;
}
else
{
return “not less than”;
}
}

Although the function contains two return statements, only one is going to be executed, depending on the values in $value1 and $value2.

Using built-in functions

PHP’s many built-in functions are one reason why PHP is so powerful and useful for Web pages. The functions included with PHP are normal functions. They are no different than functions that you create yourself. It’s just that PHP has already done all the work for you.

I discuss some of the built-in functions in this chapter and the earlier chap­ ters. For example, see Chapter 6 for more on the functions unset and number_format. Some very useful functions for interacting with your MySQL database are discussed in Chapter 8. Other useful functions are listed in
Part V of this book. And, of course, all the functions are listed and described in the PHP documentation on the PHP Web site at www.php.net/docs.php.

0 comments: