Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

Iterating Through an Array

325

Figure 6-8 Output of an associative array without advancing

the internal array pointer

One method to display the correct key for each element is to add the

next() function. The following code causes the key to be displayed

correctly, as shown in Figure 6-9:

foreach ($ProvincialCapitals as $Capital) {

echo "The capital of " .

key($ProvincialCapitals) .

" is $Capital<br />\n";

next($ProvincialCapitals);

}

Figure 6-9 Output of an associative array while advancing

the internal array pointer

If you use

an iteration

function to

move the

internal

array pointer either

before the first element

or after the last element

in an array, the only way

to move the array pointer

back to a valid element in

the array is to use the

reset() or end()

functions.


CHAPTER 6

Manipulating Arrays

To modify the MessageBoard.php file so it includes code that iterates

through $KeyMessageArray[]:

1.

2.

326

Return to the MessageBoard.php file in your text editor.

Remove the echo statements for the <pre> and </pre> tags

and the print_r() function. Remove the block comment

around the echo statement for the <table> tag, and remove

the block comments around the second for loop and the clos-

ing </table> tag from the else clause.

Between the two for loops, add the following statement to

declare and initialize a variable named $Index. You will use

the $Index variable to numerate the associative elements in

$KeyMessageArray[].

$Index = 1;

3.

4.

Modify the second for loop into the following foreach loop.

Be sure to modify the portions of the code that are high-

lighted in bold and to add the next() statement to the end of

the loop. Note that the indexes for the $CurrMsg array have

changed from 1 to 0 and from 2 to 1.

foreach($KeyMessageArray as $Message) {

$CurrMsg = explode("~", $Message);

echo "<tr>\n";

echo "<td width=\"5%\"

style=\"text-align:center\"><span

style=\"font-weight:bold\">" .

$Index . "</span></td>\n";

echo "<td width=\"85%\"><span

style=\"font-weight:bold\">

Subject:</span> " .

htmlentities(

key($KeyMessageArray)) .

"<br />";

echo "<span style=\"font-weight:bold\">

Name:</span> " .

htmlentities($CurrMsg[0]) .

"<br />";

echo "<span

style=\"text-decoration:underline;

font-weight:bold\">

Message</span><br />\n" .

htmlentities($CurrMsg[1]) .

"</td>\n";

echo "<td width=\"10%\"

style=\"text-align:center\">" .

"<a href='MessageBoard.php?" .

"action=Delete%20Message&" .

"message=" . ($Index - 1) .

"'>Delete This Message</a>" .

"</td>\n";


Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]