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

Iterating Through an Array

echo "</tr>\n";

++$Index;

next($KeyMessageArray);

}

5.

6.

Save the MessageBoard.php file and upload it to the server.

Open the MessageBoard.php file in your Web browser by

entering the following URL: http://<yourserver>/PHP_

Projects/Chapter.06/Chapter/MessageBoard.php. The mes-

sages should display normally.

Close your Web browser window.

327

7.

Another option for displaying the key and the element is to use the

advanced foreach() syntax described in Chapter 2. You recall that

the advanced syntax uses the array operator to separate the key and

element values, as in the following example. The output will be the

same as shown previously in Figure 6-9.

$ProvincialCapitals = array(

"Newfoundland and Labrador" => "St. John's",

"Prince Edward Island" => "Charlottetown",

"Nova Scotia" => "Halifax",

"New Brunswick" => "Fredericton",

"Quebec" => "Quebec City",

"Ontario" => "Toronto",

"Manitoba" => "Winnipeg",

"Saskatchewan" => "Regina",

"Alberta"=>"Edmonton",

"British Columbia" => "Victoria");

foreach ($ProvincialCapitals as $Province =>

$Capital) {

echo "The capital of $Province is

$Capital<br />\n";

}

Short Quiz

1.

2.

Describe the purpose of the internal array pointer.

Explain why you might need to use an internal array pointer

when working with associative arrays.

What is the purpose of the key() function?

When using a foreach statement to iterate through the ele-

ments of an array, what function must be used to move to the

next element in the array?

3.

4.


CHAPTER 6

Manipulating Arrays

5.

What two functions are used to move an internal array

pointer to the beginning or end of an array?

328

Finding and Extracting Elements

and Values

This section discusses methods for finding and extracting elements

and values in an array. One of the most basic methods for finding a

value in an array is to use a looping statement to iterate through the

array until you find the value. For example, the for statement in the

following code loops through the $HospitalDepts[] array to see if

it contains “Neurology”. If it does, a message displays and the break

statement ends the for loop.

$HospitalDepts = array("Anesthesia",

"Molecular Biology", "Neurology",

"Pediatrics");

for ($i = 0; $i <= count($HospitalDepts); ++$i) {

if ($HospitalDepts[$i] == "Neurology") {

echo "<p>The hospital has a Neurology

department.</p>\n";

break;

}

}

Rather than writing custom code like that in the preceding example,

you can use functions that PHP provides for finding and extracting

elements and values in an array.

Determining if a Value Exists

You can use the in_array() and array_search() functions to deter-

mine whether a value exists in an array. The in_array() function

returns a Boolean value of TRUE if a given value exists in an array. The

array_search() function determines whether a given value exists in

an array, then returns the index or key of the first matching element

if it exists or FALSE if it does not. Both functions accept two argu-

ments: The first argument represents the value to search for (some-

times called the “needle”), and the second argument represents the

name of the array in which to search (also called the “haystack”). For

example, the following code uses the in_array() function to search

for “Neurology” in the $HospitalDepts[] array. In this example, the

in_array() function is used in an if statement’s conditional expres-

sion to determine whether “Neurology” exists in the array.


Finding and Extracting Elements and Values

if (in_array("Neurology", $HospitalDepts))

echo "<p>The hospital has a Neurology

department.</p>";

The following example demonstrates how to use the array_search()

function with the $TopSellers[] array:

// This array is ordered by sales, high to low.

$TopSellers = array("Ford F-Series",

"Chevrolet Silverado", "Toyota Camry",

"Honda Accord", "Toyota Corolla",

"Honda Civic", "Nissan Altima",

"Chevrolet Impala", "Dodge Ram",

"Honda CR-V");

$SearchVehicle = "Ford F-Series";

$Ranking = array_search($SearchVehicle,

$TopSellers);

if ($Ranking !== FALSE) {

++$Ranking; // Convert the array index

//to the rank value

echo "<p>The $SearchVehicle is ranked # " .

$Ranking . " in sales for 2008.</p>\n";

}

else

echo "<p>The $SearchVehicle is not one of

the top ten selling vehicles for

2008.</p>\n";

329

In the preceding code, the comparison statement in the if statement

uses the strict not equal operator (!==). This operator is necessary

because PHP equates a Boolean value of FALSE with 0, which is also

the value that identifies the first element in an indexed array. The

strict not equal operator determines whether the 0 value assigned to

the $Ranking variable is really a Boolean value of FALSE or the index

value of 0. Because “Ford F-Series” is in the first element of the array

(which is identified with an index of 0), a numeric value of 0 (not a

Boolean value of FALSE) is assigned to the $Ranking variable.

When you work with arrays, you should always ensure that your

indexes or keys are unique. If you do not use unique values, multiple

values will be assigned to the same array index. Because the Message

Board script uses message subjects as element keys in the associa-

tive array that is displayed, you need to ensure that each subject is

unique. Remember that although the MessageBoard.php script dis-

plays the message data using an associative array, the data is stored as

individual lines in messages.txt that you convert to an indexed array

using the file() function. Because the message subject is stored in an

element in the array that is returned with the file() function, you use

the array_values() function to check whether the subject exists as a

value in the array.


CHAPTER 6

Manipulating Arrays

To modify the Message Board script so that users can only enter

unique subjects:

1.

2.

330

Open the PostMessage.php file in your text editor.

Add the following statements before the statement that

declares and initializes the $MessageRecord variable. The

first statement declares and initializes an empty array

named $ExistingSubjects that you will use to determine

whether a subject already exists. The if statement is very

similar to the code in the MessageBoard.php file. First, the

conditional expression checks whether the messages.txt file

exists and if it is larger than 0 KB. If the condition evaluates

to TRUE, the file() function assigns the text in messages.txt

to $MessageArray[]. The for loop then explodes each ele-

ment in $MessageArray[] into the $CurrMsg[] array. Finally,

the subject, which is stored in $CurrMsg[0], is added to the

$ExistingSubjects array.

$ExistingSubjects = array();

if (file_exists(

"MessageBoard/messages.txt") &&

filesize("MessageBoard/messages.txt")

> 0) {

$MessageArray = file(

"MessageBoard/messages.txt");

$count = count($MessageArray);

for ($i = 0; $i < $count; ++$i) {

$CurrMsg = explode("~",

$MessageArray[$i]);

$ExistingSubjects[] = $CurrMsg[0];

}

}

3.

Immediately after the preceding code, add the following if

statement, which uses the in_array() function to determine

if the entered subject is found in the $ExistingSubjects

array. If the subject already exists, an error message is dis-

played and the $Subject variable is set to an empty string.

if (in_array($Subject, $ExistingSubjects)) {

echo "<p>The subject you entered

already exists!<br />\n";

echo "Please enter a new subject and

try again.<br />\n";

echo "Your message was not saved.</p>";

$Subject = "";

}

4.

Add the following code shown in bold. These changes place

the existing code, which saves the record to messages.txt, into

an else clause for the preceding if statement. Add two new


Finding and Extracting Elements and Values

lines to set the $Subject and $Message variables to an empty

string if the message was successfully saved. The code should

appear as follows, with the new code in bold:

else {

$MessageRecord =

"$Subject~$Name~$Message\n";

$MessageFile = fopen(

"MessageBoard/messages.txt",

"ab");

if ($MessageFile === false)

echo "There was an error saving

your message!\n";

else {

fwrite($MessageFile,

$MessageRecord);

fclose($MessageFile);

echo "Your message has been

saved.\n";

$Subject = "";

$Message = "";

}

}

331

5.

Just before the closing tag for the PHP code block, insert the

following else clause to the if (isset($_POST['submit']))

statement. These lines clear out the $Subject, $Name, and

$Message variables if there is no posted data.

else {

$Subject = "";

$Name = "";

$Message = "";

}

The PHP code block should appear as follows:

<?php

if (isset($_POST['submit'])) {

$Subject = stripslashes($_POST['subject']);

$Name = stripslashes($_POST['name']);

$Message = stripslashes($_POST['message']);

// Replace any '~' characters

//with '-' characters

$Subject = str_replace("~", "-", $Subject);

$Name = str_replace("~", "-", $Name);

$Message = str_replace("~", "-", $Message);

$ExistingSubjects = array();

if (file_exists(

"MessageBoard/messages.txt") &&

filesize("MessageBoard/messages.txt")

> 0) {


CHAPTER 6

Manipulating Arrays

$MessageArray = file(

"MessageBoard/messages.txt");

$count = count($MessageArray);

for ($i = 0; $i < $count; ++$i) {

$CurrMsg = explode("~",

$MessageArray[$i]);

$ExistingSubjects[] = $CurrMsg[0];

}

}

if (in_array($Subject, $ExistingSubjects)) {

echo "<p>The subject you entered

already exists!<br />\n";

echo "Please enter a new subject and

try again.<br />\n";

echo "Your message was not saved.</p>";

$Subject = "";

}

else {

$MessageRecord =

"$Subject~$Name~$Message\n";

$MessageFile =

fopen("MessageBoard/messages.txt",

"ab");

if ($MessageFile === FALSE)

echo "There was an error saving your

message!\n";

else {

fwrite($MessageFile, $MessageRecord);

fclose($MessageFile);

echo "Your message has been saved.\n";

$Subject = "";

$Message = "";

}

}

}

else {

$Subject = "";

$Name = "";

$Message = "";

}

?>

332

6.

Make the changes shown below in bold to convert the Web

form into a sticky form.

<span style="font-weight:bold">Subject:</span>

<input type="text" name="subject"

value="<?php echo $Subject; ?>" />

<span style="font-weight:bold">Name:</span>

<input type="text" name="name"

value="<?php echo $Name; ?>" /><br />

<textarea name="message" rows="6"

cols="80"><?php echo $Message;

?></textarea><br />


Finding and Extracting Elements and Values

7.

8.

Save the PostMessage.php file and upload it to the server.

Open the PostMessage.php file in your Web browser by enter-

ing the following URL: http://<yourserver>/PHP_Projects/

Chapter.06/Chapter/PostMessage.php. Add a new message.

Try adding another message with exactly the same subject

as the message you just entered. You should see a message in

the Post Message form handler page informing you that the

subject already exists. Figure 6-10 shows an attempt to post

another message with the subject “String Question”. Notice

that the Subject field has been cleared because of the error,

but the other fields have been maintained.

333

Figure 6-10

9.

The error message for a duplicated subject when posting a new message

Close your Web browser window.

Determining if a Key Exists

In addition to determining whether a specific value exists in an

array, you can also use the array_key_exists() function to deter-

mine whether a given index or key exists. You pass two arguments

to the array_key_exists() function: The first argument represents

the key to search for (the needle), and the second argument repre-

sents the name of the array in which to search (the haystack). As an

example, suppose you develop an online chat room in which only

members can post messages. Each visitor selects a “screen name”

CHAPTER 6

Manipulating Arrays

334

when he or she joins. Now suppose that the screen name is an ele-

ment’s key in an associative array, and the name of the member who

selected the screen name is the element’s value. Before assigning

a member to a particular screen name in the array, you could use

the array_key_exists() function to determine whether another

member has already selected that screen name. The following code

shows some screen names that are assigned to an array named

$ScreenNames[]. Before allowing a new member to have the screen

name “Fat Man,” the if statement uses the array_key_exists()

function to determine whether the array element already exists.

$ScreenNames["Dancer"] = "Daryl";

$ScreenNames["Fat Man"] = "Dennis";

$ScreenNames["Assassin"] = "Jennifer";

if (array_key_exists("Fat Man", $ScreenNames))

echo "<p>{$ScreenNames['Fat Man']} is

already 'Fat Man'.</p>\n";

else {

$ScreenNames["Fat Man"] = "Don";

echo "<p>{$ScreenNames['Fat Man']} is now

'Fat Man'.</p>";

}

You can use the array_keys() function to return an indexed array

that contains all the keys in an associative array, as shown in the fol-

lowing example. A new indexed array named $UsedScreenNames[],

which contains the keys from the $ScreenNames[] array, is created

with the array_keys() function. A for loop then displays the values

in the $UsedScreenNames[] array.

$ScreenNames["Dancer"] = "Daryl";

$ScreenNames["Fat Man"] = "Dennis";

$ScreenNames["Assassin"] = "Jennifer";

$UsedScreenNames = array_keys($ScreenNames);

echo "<p>The following screen names are already

assigned:</p>\n";

for ($i = 0; $i < count($UsedScreenNames);

++$i) {

echo "<p>{$UsedScreenNames[$i]}</p>\n";

}

You can also pass a second argument to the array_keys() function

that specifies an element value for which to search. These keys are

returned only for elements that match the specified value.

Returning a Portion of an Array

You use the array_slice() function to return (copy) a portion of

an array and assign it to another array. The syntax for the function

is array_slice(array_name, start_index, number_to_return);.


Finding and Extracting Elements and Values

The array_name argument indicates the name of the array from

which you want to extract elements. The start_index argument

indicates the start position within the array to begin extracting ele-

ments. The number_to_return argument is an integer value that

indicates the number of elements to return from the array, start-

ing with the element indicated by the start_index argument. The

syntax for returning a portion of an array with the array_slice()

function is very similar to the syntax for deleting a portion of an

array with the array_splice() function. The main difference is

that the array_splice() function removes elements, while the

array_slice() function returns an array containing those elements.

The following example demonstrates how to use the array_slice()

function to return the first five elements in the $TopSellers[]

array. The elements are assigned to a new element named

$FiveTopSellers[]. Figure 6-11 shows the output.

// This array is ordered by sales, high to low.

$TopSellers = array("Ford F-Series",

"Chevrolet Silverado", "Toyota Camry",

"Honda Accord", "Toyota Corolla",

"Honda Civic", "Nissan Altima",

"Chevrolet Impala", "Dodge Ram",

"Honda CR-V");

$FiveTopSellers = array_slice($TopSellers, 0, 5);

echo "<p>The five best-selling vehicles for

2008 are:</p>\n";

for ($i = 0; $i < count($FiveTopSellers); ++$i) {

echo "{$FiveTopSellers[$i]}<br />\n";

}

335

Figure 6-11

Output of an array returned with the array_slice() function


CHAPTER 6

Manipulating Arrays

Short Quiz

1.

336

Differentiate between the value returned by the in_array()

function and the array_search() function.

What function can be used to return an indexed array of all

keys in an associative array?

What does the array_key_exists() function do?

What function is used to return a portion of an array and

assign it to another array?

2.

3.

4.

Manipulating Arrays

In the preceding section, you studied techniques for working with

the individual elements in an array. In this section, you will study

techniques for manipulating entire arrays, including how to sort,

combine, and compare arrays.

Sorting Arrays

You sort arrays using the functions listed in Table 6-2.

Function

array_multisort(array[,

array, ...])

arsort(array[, SORT_REGULAR |

SORT_NUMERIC | SORT_STRING])

asort(array[, SORT_REGULAR |

SORT_NUMERIC | SORT_STRING])

krsort(array[, SORT_REGULAR |

SORT_NUMERIC | SORT_STRING])

ksort(array[, SORT_REGULAR |

SORT_NUMERIC | SORT_STRING])

natcasesort(array)

natsort(array)

Description

Sorts multiple arrays or multidimensional arrays

Sorts an array in descending order (largest to smallest) by

value and maintains the existing keys for an associative array

Sorts an array in ascending order (smallest to largest) by

value and maintains the existing keys for an associative array

Sorts an array in descending order by key and maintains the

existing keys for an associative array

Sorts an array in ascending order by key and maintains the

existing keys for an associative array

Performs a case-sensitive natural order sort by value and

maintains the existing keys for an associative array

Performs a case-insensitive natural order sort by value and

maintains the existing keys for an associative array

Table 6-2

Array sorting functions (continues)

Manipulating Arrays

(continued)

Function

rsort(array[, SORT_REGULAR |

SORT_NUMERIC | SORT_STRING])

sort(array[, SORT_REGULAR |

SORT_NUMERIC | SORT_STRING])

uaksort(array[,

comparison_function])

uksort(array[,

comparison_function])

usort(array[,

comparison_function])

Description

Sorts an array in descending order by value, removes any

existing keys for an associative array, and renumbers the

indexes starting with 0

Sorts an array in ascending order by value, removes any

existing keys for an associative array, and renumbers the

indexes starting with 0

Sorts an array in ascending order by value using a

comparison function and maintains the existing keys for an

associative array

Sorts an array in ascending order by key using a comparison

function and maintains the existing keys for an associative

array

Sorts an array in ascending order by value using a

comparison function, removes any existing keys for an

associative array, and renumbers the indexes starting with 0

337

Table 6-2

Array sorting functions

The most commonly used array sorting functions are sort() and

rsort() for indexed arrays, and asort(), arsort(), ksort(), and

krsort() for associative arrays. These functions operate directly

on an array, not on a new copy of an array, as occurs with the

array_values() function. This means that you can execute each

function simply by passing the name of an array to it.

The two “natural order” sort functions, natsort() and natcasesort(),

use a special sorting algorithm. Rather than sorting only on the ASCII

values of the corresponding characters, the algorithm treats one or

more successive numeric characters as an integer value and sorts by

integer value. For example, consider the following array of message

filenames:

$MessageFiles = array(

"message5.txt",

"message3.txt",

"message6.txt",

"message1.txt",

"message9.txt",

"message4.txt",

"message7.txt",

"message2.txt",

"message8.txt",

"message10.txt");


CHAPTER 6

Manipulating Arrays

338

If you used the sort() function on this array, the values would appear

in the order “message1.txt”, “message10.txt”, “message2.txt”, . . . ,

“message9.txt”. Although this ordering is correct when looking at the

ASCII values, it is not the expected result. If you used the natsort()

function instead, the values would appear in the order “message1.txt”,

“message2.txt”, . . . , “message9.txt”, “message10.txt”, because “10” is a

larger numeric value than any of the other numeric values.

Keep in mind that the sort function you use depends on whether

you need to sort an indexed or associative array. For example, the

sort() and rsort() functions sort indexed arrays and renumber the

element indexes. The following code demonstrates how to sort the

indexed $FiveTopSellers array in ascending and descending order.

Figure 6-12 shows the output.

// This array is ordered by sales, high to low.

$TopSellers = array("Ford F-Series",

"Chevrolet Silverado", "Toyota Camry",

"Honda Accord", "Toyota Corolla",

"Honda Civic", "Nissan Altima",

"Chevrolet Impala", "Dodge Ram",

"Honda CR-V");

$FiveTopSellers = array_slice($TopSellers, 0, 5);

echo "<p>The five best-selling vehicles for 2008

by number of vehicles sold are:</p>\n";

for ($i = 0; $i < count($FiveTopSellers); ++$i) {

echo "{$FiveTopSellers[$i]}<br />\n";

}

echo "</p>";

sort($FiveTopSellers);

echo "<p> The five best-selling vehicles for 2008

in alphabetical order are:</p><p>";

for ($i = 0; $i < count($FiveTopSellers); ++$i) {

echo "{$FiveTopSellers[$i]}<br />";

}

echo "</p>";

rsort($FiveTopSellers);

echo "<p>The five best-selling vehicles for 2008

in reverse alphabetical order are:</p><p>";

for ($i = 0; $i < count($FiveTopSellers); ++$i) {

echo "{$FiveTopSellers[$i]}<br />";

}

echo "</p>";


Manipulating Arrays

339

Figure 6-12 Output of an array after applying the sort() and

rsort() functions

If you use

the sort()

and

rsort()

functions on

an associative array, the

keys are replaced with

sequential indexes start-

ing with 0.

To modify MessageBoard.php to use the sort() function to sort the

messages in the Message Board script by subject in ascending order:

1.

2.

Reopen MessageBoard.php in your text editor.

Add the following code as a fifth case to the switch() state-

ment. This case uses the sort() function to sort the array in

ascending order.

case 'Sort Ascending':

sort($MessageArray);

break;

3.

Modify the paragraph element at the end of the file so

that it contains another anchor element that calls the

MessageBoard.php file with the proper parameters to sort

the messages in ascending order, as follows:


CHAPTER 6

Manipulating Arrays

<p>

<a href="PostMessage.php">

Post New Message</a><br />

<a href=

"MessageBoard.php?action=Sort%20Ascending">

Sort Subjects A-Z</a><br />

<a href=

"MessageBoard.php?action=Remove%20Duplicates">

Remove Duplicate Messages</a><br />

<a href="MessageBoard.php?action=Delete%20First">

Delete First Message</a><br />

<a href="MessageBoard.php?action=Delete%20Last">

Delete Last Message</a>

</p>

340

4.

Save the MessageBoard.php file and upload it to the Web

server.

Open the MessageBoard.php file in your Web browser by

entering the following URL: http://<yourserver>/PHP_

Projects/Chapter.06/Chapter/MessageBoard.php. Click the

Sort Subjects A-Z link to test the new code. The message list

should sort by subject in ascending order.

Close your Web browser window.

5.

6.

The following code includes a statement that uses the sort() func-

tion on the $ProvincialCapitals[] array you saw earlier. Recall that

with this array, province names are used as element keys. However,

the sort() function in the following code replaces the keys with

indexes, as shown in Figure 6-13.

$ProvincialCapitals = array(

"Newfoundland and Labrador" => "St. John's",

"Prince Edward Island" => "Charlottetown",

"Nova Scotia" => "Halifax",

"New Brunswick" => "Fredericton",

"Quebec" => "Quebec City",

"Ontario" => "Toronto",

"Manitoba" => "Winnipeg",

"Saskatchewan" => "Regina",

"Alberta" => "Edmonton",

"British Columbia" => "Victoria");

sort($ProvincialCapitals);

echo "<pre>\n";

print_r($ProvincialCapitals);

echo "</pre>\n";


Manipulating Arrays

341

Figure 6-13 Output of an associative array after sorting

with the sort() function

To sort an associative array by value and maintain the existing keys,

you use the asort() function, as follows:

asort($ProvincialCapitals);

echo "<pre>\n";

print_r($ProvincialCapitals);

echo "</pre>\n";

The asort() function in the preceding code sorts the values and

maintains the existing keys, as shown in Figure 6-14.

Figure 6-14 Output of an associative array after sorting

with the asort() function

CHAPTER 6

Manipulating Arrays

To perform a reverse sort on an associative array and maintain the

existing keys, be sure to use the arsort() function, not the rsort()

function. The following statement demonstrates how to perform a

reverse sort on the $ProvincialCapitals[] array:

arsort($ProvincialCapitals);

342

To sort an associative array by key and maintain the existing keys, you

use the ksort() function, as follows:

ksort($ProvincialCapitals);

echo "<pre>\n";

print_r($ProvincialCapitals);

echo "</pre>\n";

The ksort() function in the preceding code sorts and maintains the

existing keys, as shown in Figure 6-15.

Figure 6-15 Output of an associative array after sorting

with the ksort() function

To perform a reverse sort on an associative array by key and main-

tain the existing keys, use the krsort() function. The following

statement demonstrates how to perform a reverse sort on the

$ProvincialCapitals[] array:

krsort($ProvincialCapitals);

To modify MessageBoard.php to use the rsort() function to sort the

messages in the Message Board script by subject in descending order:

1.

Reopen MessageBoard.php in your text editor.

Manipulating Arrays

2.

Add the following code as a sixth case to the switch() state-

ment. This case uses the rsort() function to sort the array in

descending order.

case 'Sort Descending':

rsort($MessageArray);

break;

343

3.

Modify the paragraph element at the end of the file so

that it contains another anchor element that calls the

MessageBoard.php file with the proper parameters to sort

the messages in descending order, as follows:

<p>

<a href="PostMessage.php">

Post New Message</a><br />

<a href=

"MessageBoard.php?action=Sort%20Ascending">

Sort Subjects A-Z</a><br />

<a href=

"MessageBoard.php?action=Sort%20Descending">

Sort Subjects Z-A</a><br />

<a href=

"MessageBoard.php?action=Remove%20Duplicates">

Remove Duplicate Messages</a><br />

<a href="MessageBoard.php?action=Delete%20First">

Delete First Message</a><br />

<a href="MessageBoard.php?action=Delete%20Last">

Delete Last Message</a>

</p>

4.

Save the MessageBoard.php file and upload it to the Web

server.

Open the MessageBoard.php file in your Web browser by

entering the following URL: http://<yourserver>/PHP_

Projects/Chapter.06/Chapter/MessageBoard.php. Click the

Sort Subjects Z-A link to test the new code. The message list

should sort by subject in descending order.

Close your Web browser window.

5.

6.

You can

use the

shuffle()

function to

randomize the

order of array elements.

The shuffle() function

removes any existing

keys from an associative

array, and renumbers the

indexes starting with 0.

Combining Arrays

If you want to combine arrays, you have two options. You can either

append one array to another or merge the two arrays. To append

one array to another, you use the addition (+) or additive compound

assignment operator (+=). Unlike in arithmetic addition, order is

important when appending one array to another array. The array on

the left side of the operator is the primary array, or the array that

PHP starts with. The array on the right side of the operator is the


CHAPTER 6

Manipulating Arrays

secondary array, or the array being appended to the primary array.

344

When you use either operator, PHP ignores any array elements in the

secondary array where the indexes or keys already exist in the pri-

mary array. Because indexed arrays start at 0 by default, the addition

operators are not an effective way of merging indexed arrays. This

method works well for associative arrays, as long as none of the asso-

ciative array keys of one array is found in the other array.

To help illustrate that addition operators do not work well for

indexed arrays, consider the following code, which declares and ini-

tializes $Provinces[] and $Territories[] as indexed arrays. The

$Territories[] array is appended to the $Provinces[] array with

the addition (+) operator, and the resulting array is assigned to an

array named $Canada[]. However, notice in Figure 6-16 that the

$Canada[] array only contains the elements that were assigned to

the $Provinces[] array. This occurs because the three indexes in the

$Territories[] array (0, 1, and 2) already exist in the $Provinces[]

array and are therefore ignored.

$Provinces = array("Newfoundland and Labrador",

"Prince Edward Island", "Nova Scotia",

"New Brunswick", "Quebec", "Ontario",

"Manitoba", "Saskatchewan", "Alberta",

"British Columbia");

$Territories = array("Nunavut",

"Northwest Territories", "Yukon Territory");

$Canada = $Provinces + $Territories;

echo "<pre>\n";

print_r($Canada);

echo "</pre>\n";

Figure 6-16 Output of two indexed arrays combined with the

addition operator


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