Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu PHP and MySQL by Example- P7 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.64 MB, 50 trang )



Example 8.36.
<html>
<head><title>Random Array of Two Strings</title></head>
<body bgcolor="lightgreen">
<font face="verdana" size="+1">
<?php
1 $sayings=array("An apple a day keeps the doctor away",
"Too many cooks spoil the broth",
"A stitch in time saves 9",
"Don't put the cart before the horse",
);
2 $selection = array_rand($sayings,2);
3 print "${sayings[$selection[0]]}.<br />";
print "${sayings[$selection[1]]}.<br />";
?>
</body>
</html>
Explanation
1
The!array!called!$sayings!is!assigned!a!list!of!strings.
2
The!array_rand()!function!is!given!a!second!argument,!the!number!2,!which!is!the!
number!of!random!items!to!return.!The!array!called!$selection!will!contain!another!
array!of!two!random!key/index!values.
3
The!first!and!second!randomly!selected!strings!are!printed.!The!value!of!$selection[0]!
is!a!random!index!number.!So!is!the!value!of!$selection[1].!By!using!those!array!
elements!as!indexes!for!the!$sayings!array,!a!randomized!string!will!be!returned.!Notice!
the!curly!braces!surrounding!the!$sayings!array.!The!curly!braces!block!the!array!


elements!so!that!the!first!$!applies!to!the!whole!array.!If!you!remove!the!curly!braces,!
you!will!get!an!error.!The!other!way!to!print!this!would!be!to!remove!the!quotes:!!
print $sayings[$selection[1]] . ".<br />";
!
See!Figures!8.43!and!8.44.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.43. Selecting two random elements from an array. Output from Example 8.36.

!
Figure 8.44. Refreshing the screen for two more random elements.


Shuffling a Numeric Array (Randomizing the Values)
The shuffle() function causes the elements of a numerically indexed array to be randomized. It randomizes the
values of an associative array, but destroys the keys. The function returns boolean TRUE or FALSE. See Example 8.37.
Prior to PHP 4.2.0, it was necessary to seed the random number generator (give it a different starting point) with
srand(), but now that is done automatically. To randomize a selected number of elements of an array, see the
array_rand() function.
Format
boolean_value = shuffle( array_name );
!
Example:
$numbers = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); shuffle($numbers);
!
Output:
9 4 6 5 1 3 2 8 7 10
Example 8.37.
<html><head><title>Shuffle the Array</title></head>
<body bgcolor="33FF66">

<div align="center">
<font size="+1">
<h3>
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Shuffle the Array
</h3>
<?php
1 $months=range(1,12);
2 // srand(time());
echo "<b>Before:</b> ", implode(", ", $months), "<br /><br
/>";
3 shuffle($months);
echo "<b>After: </b>", implode(", ", $months), "<br />";
?>
</font>
</div>
</body>
</html>
Explanation
1
An!array!called!$months!is!created.!A!range!of!1!to!12!months!is!created!with!the!range()!
function.
2
It!is!no!longer!necessary!to!seed!the!random!number!generator!with!srand();!that!is,!give!it!
a!random!starting!point.
3
The!shuffle()!function!shuffles!or!randomizes!the!elements!of!the!array,!$months.!See!
Figure!8.45!for!before!and!after!the!shuffle.
!
Figure 8.45. Shuffling an array of months. Output from Example 8.37.

!



Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
8.2. Modifying Arrays (Unsetting, Deleting, Adding, and Changing Elements)
PHP makes it easy to modify both numeric and associative arrays by providing a number of built-in functions to add
new elements, remove existing elements and/or replace those elements with new ones, copy elements from one array to
another, to rearrange elements, and so on.
8.2.1. Removing an Array and Its Elements
There are a number of built-in functions to remove elements from an array (see Table 8.8).
Table 8.8. Functions That Remove Elements
Function
What+It+Does
array_pop()
Removes!and!returns!the!last!element!of!an!array
array_shift()
Removes!and!returns!the!first!element!of!an!array
array_splice()
Removes!and/or!replaces!elements!in!an!array
array_unique()
Removes!duplicates!from!an!array
!
Removing an Entire Array
The unset() function completely removes an array, as though it never existed. Setting the element’s value to zero or
the null string assumes the element is still there.
Format
void unset ( mixed var [, mixed var [, mixed ]] )
!
Example:

$colors=array("red","green","blue"); unset($colors); // Removes the array

Removing the Last Element of an Array
The array_pop() function removes the last elment of an array and returns it, shortening the array by one element. If
the array is empty (or is not an array), NULL will be returned. This function resets the array pointer after it is used.
Format
mixed array_pop ( array &array )
!
Example:
$animals = ("dog", "cat", "pig", "cow"); $strayed = array_pop($animals); // The
"cow" is removed from the // array, and assigned
to $strayed

Example 8.38.
<html><head><title>array_pop()</title></head>
<body bgcolor="cccc99">
<font face="verdana" size="+1">
<?php
echo "Before pop(): ";
1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");
2 foreach($names as $val){
echo "<em>$val </em>";
}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
3 $popped = array_pop($names); // Remove last element
echo "<br />After pop(): ";
4 foreach($names as $val){
echo "<em>$val </em>";
}
echo "<p>$popped was removed from the end of the

array.</p>";
?>
</pre>
</body>
</html>
Explanation
1
The!numeric!array!$names!is!created!and!assigned!a!list!of!values.
2
The!foreach!loop!is!used!to!iterate!through!the!array!and!display!its!values.
3
The!array_pop()!function!removes!the!last!element!of!the!array,!"Jerry".!The!popped!
off!value!is!returned!and!assigned!to!a!variable,!called!$popped.
4
The!$names!array!is!displayed!after!the!last!element!was!removed!with!the!
array_pop()!function.!See!Figure!8.46.
!
Figure 8.46. The last element from an array is removed with pop(). Output from Example 8.38.


Removing the First Element of an Array
The array_shift() function removes the first element from an array and returns it, decreasing the size of the array
by one element. All numerical array keys start at zero and literal keys will not be touched. If an array is empty (or is not
an array), NULL will be returned. See Example 8.39.
Format
mixed array_shift ( array &array )
!
Example:
$colors=array("red", "blue","green", "yellow"); // First element, "red", removed
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

and assigned to $shifted_off_color $shifted_off_color = array_shift( $colors);
Example 8.39.
<html><head><title>array_shift()</title></head>
<body bgcolor="lightblue">
<font face="verdana" size="+1">
<?php
echo "Before the shift: ";
1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");
2 foreach($names as $val){
echo "<em>$val </em>";
}
3 $shifted=array_shift($names); // Remove first element
echo "<br />After the shift: ";
4 foreach($names as $val){
echo "<em>$val </em>";
}
5 echo "<p>$shifted was removed.</p>";
?>
</pre>
</body>
</html>
Explanation
1
A!numeric!array!called!$names!is!defined.
2
The!foreach!loop!is!used!to!iterate!through!the!array!and!get!the!individual!
values,!each!one!in!turn,!assigned!to!$val.
3
The!array_shift()!function!removes!and!returns!the!first!element!of!the!
array,!"Tom",!assigned!to!$shifted.

4
The!foreach!loop!is!used!again!to!iterate!through!the!array!showing!that!the!
array!has!been!shortened!by!one!element.!See!Figure!8.47.
5
The!value!returned!from!the!array_shift()!function!is!"Tom",!the!first!
element!in!the!array.!This!value!is!printed.!See!Figure!8.47.
Figure 8.47. Removing the first element of an array with shift(). Output from Example 8.39.

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Removing Duplicate Values from an Array
The array_unique() function removes duplicate values from an array and returns a new array without the
duplicates. The array_unique() function first sorts the values treated as strings, then keeps the first key
encountered for every value, and thereafter, ignores any duplicate keys. Two elements are considered equal only if they
are identical (same data type, same value); that is, the === operator applies. See Example 8.40.
Format
array array_unique ( array array )
!
Example:
unique_values = array_unique(array("apples", "pears",
"apples", "Apples")); // Removes duplicates and returns an array with unique
values.
Example 8.40.
<html><head><title>array_unique()</title></head>
<body bgcolor="cccc99">
<font face="verdana" size="+1">
<?php
echo "Before: ";
1 $numbers=array(1, 3, 5, 7, 7, 7, 9, 9, 8);
2 foreach($numbers as $val){
echo "<em>$val </em>";

}
echo "<br />After: ";
3 $numbers=array_unique($numbers); // Remove duplicates
echo '$numbers=<b>array_unique($numbers)i</b><br />';
foreach($numbers as $val){
echo "<em>$val </em>";
}
?>
</pre>
</body>
</html>
Explanation
1
A!numerically!indexed!array!called!$numbers!is!assigned!a!list!of!integers.
2
The!foreach!loop!is!used!to!loop!through!the!array,!$numbers.!The!value!of!each!of!the!
elements!is!printed.
3
Notice!that!there!are!a!number!of!duplicate!values!in!the!array!$numbers.!The!
array_unique!function!returns!an!array!with!duplicates!removed;!that!is,!an!array!of!
unique!values.!See!Figure!8.48.
!







Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Figure 8.48. The array_unique() function. Output from Example 8.40.
!
8.2.2. Adding Elements to an Array
PHP provides built-in functions to increase the size of an array by allowing you to add elements.(see Table 8.9).
Table 8.9. Array Functions to Add Elements to an Array
Function
What+It+Does
array_push()
Pushes!a!new!element(s)!onto!the!end!of!the!array
array_splice()
Removes!and/or!adds!elements!to!an!array!at!any!position
array_unshift()
Adds!a!new!element(s)!to!the!beginning!of!the!array
!
Adding Elements to the Beginning of an Array
The array_unshift() function prepends one or more elements onto the beginning of an array, increasing the size
of the array by the number of elements that were added. It returns the number of elements that were added. See
Example 8.41.
Format
int array_unshift ( array &array, mixed var [, mixed ] )
!
Example:
$colors=("yellow", "blue", "white");
$added=array_unshift($colors,"red","green"); // "red", "green", "yellow",
"blue", "white"

Example 8.41.
<html><head><title>array_unshift()</title></head>
<body bgcolor="yellow">
<font face="verdana" size="+1">

<?php
echo "Before unshift(): ";
1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
2 foreach($names as $val){
echo "<em>$val </em>";
}
// Add new element to the beginning
3 array_unshift($names, "Willie", "Liz");
echo "<br />After unshift(): ";
foreach($names as $val){
echo "<em>$val </em>";
}
4 echo "<p>Willie and Liz were added to the beginning of the
array.</p>";
?>
</pre>
</body>
</html>




Explanation
1
The!numeric!array!called!$names!is!assigned!five!string!values.
2
The!foreach!loop!is!used!to!iterate!through!the!array!$names.!Each!value!is!printed!as!
the!loop!cycles!through!the!array.
3

The!array_unshift()!function!is!used!to!append!new!elements!to!the!beginning!of!an!
array.!In!this!example,!"Willie"!and!"Liz"!are!prepended!to!the!array!$names.
"Willie"!will!be!assigned!the!index!of!0,!and!all!the!rest!of!the!index!values!will!be!
incremented!accordingly.
4
Figure!8.49!displays!the!array!after!"Willie"!and!"Liz"!are!prepended!with!the!
array_unshift()!function.
!
Figure 8.49. Adding elements to the beginning of an array with unshift(). Output from Example 8.41.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Adding Elements to the End of an Array
The array_push() function pushes one or more elements onto the end of array, increasing the size of the array by
the number of elements that were added. It returns the number of elements that were added. See Example 8.42.
Format
int array_push ( array &array, mixed var [, mixed ] )
!
Example:
$colors=("yellow", "blue", "white"); $added = array_push($colors, "red",
"green"); // "yellow", "blue", "white", "red", "green"
Example 8.42.
<html><head><title>array push()</title></head>
<body bgcolor="lightblue">
<font face="verdana" size="+1">
<?php
echo "Before push(): ";
1 $names=array("Tom", "Dan", "Christian", "Jerry");
2 foreach($names as $val){
echo "<em>$val </em>";
}

3 array_push($names, "Tina", "Donna");// Add two elements
echo "<br />After push(): ";
foreach($names as $val){
echo "<em>$val </em>";
}
4 echo "<p>Tina and Donna were added to the end of the
array.</p>";
?>
</pre>
</body>
</html>
Explanation
1
The!numeric!array!called!$names!is!assigned!four!string!values.
2
The!foreach!loop!is!used!to!iterate!through!the!array!$names.!Each!value!is!printed!as!
the!loop!cycles!through!the!array.
3
The!array_push()!function!is!used!to!append!new!elements!to!the!end!of!an!array.!In!
this!example,!"Tina"!and!"Donna"!are!appended!to!the!array!$names. "Tom"!will!be!
assigned!the!index!of!0,!and!all!the!rest!of!the!index!values!are!incremented!accordingly.
4
Figure!8.50!displays!the!array!after!"Tina"!and!"Donna"!are!appended!to!it!with!the!
array_push()!function.
!






Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.50. The array_push() function. Output from Example 8.42.
!



Splicing an Array—Removing and Adding Elements
The word splice is often associated with splicing two pieces of rope, film, or DNA strands. It means to join. Array
elements can be removed and then what is left can be joined back together. The array_splice() function removes
a portion of the array and joins it back together, possibly replacing the removed values with new ones. The first
argument is the array, and the second argument is the place in the array (called the offset) where you want the function
to start removing elements. Offset 0 is the first position in the array. If you are taking elements from the end of the
array, the offset starts at a negative number. An offset of –1 indicates the end of the array. The third, optional argument
tells the function how many elements you want to remove. If you do not specify a length, splice() removes
everything from the offset to the end of the array. A fourth optional argument allows you to list the replacement values.
(Use the built-in count() function to get the length of the array.) The returned values are the elements that were
removed.
Simply put, splice() removes any number of elements from an array, starting at some position, and lets you replace
those elements with new ones if you want to.
The next set of examples demonstrate how array_splice() is used to remove and replace elements in an array.
Figure 8.51 displays the resulting spliced array.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.51. The splice() function. Each numbered example is applied to the original array.
!
!
Format
array array_splice ( array &input, int offset [, int length [,
array replacement]] )
!
Examples:

1. $foods=array("bread","milk", "eggs", "fruit", "meat");
array_splice($foods, 4); // Removes "meat" 2. $foods=array("bread","milk",
"eggs", "fruit", "meat"); array_splice($foods,0,3); // Removes "bread",
"milk", and "eggs" 3. $foods=array("bread","milk", "eggs", "fruit", "meat");
array_splice($foods, -2); // Removes "fruit" and "meat" 4.
$foods=array("bread","milk", "eggs", "fruit", "meat"); array_splice($foods,
0,0, array("fish", "cheese")); // Prepends the array with "fish" and
"cheese" 5. $foods=array("bread","milk", "eggs", "fruit", "meat");
array_splice($foods, -3, 2, "veggies"); // Backs up three from the end,
removes "eggs" and "fruit", // and replaces them with "veggies" 6.
$foods=array("bread","milk", "eggs", "fruit", "meat"); array_splice($foods,2
,count($foods),array("beer","peanuts")); // Removes "eggs", "fruit", and
"meat" and replaces them with // "beer" and "peanuts"


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

8.2.3. Copying Elements of an Array
The array_slice() Function
In case you get the terms splice and slice confused, think of a splice as joining two pieces of tape or rope together and
think of slice as in a slice of bread or a slice of apple pie. The array_slice() function extracts a slice (some
specified elements) of an array, specified by an offset and the number of elements to extract. It returns the specified
sequence of elements from the array and resets the key/index values. If the boolean argument is set to TRUE, then the
index values will not be adjusted.
To simplify, the array_slice() function copies elements from one array, and assigns them to another array. The
array that is being sliced is not changed. See Example 8.43
Format
array array_slice ( array array, int offset [, int length [,
bool preserve_keys]] ) array = array_slice ( array_name, integer offset); array
= array_slice ( array_name, integer offset, length); array = array_slice (

array_name, integer offset, length, boolean value);
!
Example:
foods = array("bread", "milk", "eggs", "fruit"); $slice = array_slice ( $foods,
2); // $slice contains "eggs" $slice = array_slice ( $foods, 0, 2); // $slice
contains "bread" and "milk" $slice = array_slice ( $foods, -2, 1); // $slice
contains "milk" $slice = array_slice ( $foods, 0, 3, TRUE); // $slice contains
"bread", "milk", and "eggs"; the order of the // keys/index values are preserved

Example 8.43.
Code!View:!
<html><head><title>array_slice()</title></head>
<body bgcolor="cccc99">
<font face="verdana">
<pre>
<b>
<?php
1 $names=array("Tom", "Dan", "Steve", "Christian", "Jerry");
echo "Original array before slice(): <br />";
print_r($names);
2 $good_guys=array_slice($names, 0, 3);
echo "<br />New array from array_slice(0,3):<br /> ";
print_r($good_guys);
3 $chosen_ones=array_slice($names, -2);
echo "New array from array_slice(-2):<br />";
print_r($chosen_ones);
echo "Original array after the slice(): <br />";
4 print_r($names);
?>
</pre>

<b>
</body>
</html>! ! ! ! !!



Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Explanation
1
$names!is!a!numeric!array!intialized!with!a!list!of!strings.
2
The!first!argument!to!the!array_slice()!function!is!the!offset!position,!where!
to!start!selecting!elements,!and!the!second!argument!is!the!length!or!number!
of!elements!to!copy.!In!this!example,!"Tom", "Dan",!and!"Steve"!are!copied!
into!an!array!called!$good_guys.
3
In!this!example,!the!offset!starts!from!the!end!of!the!array.!An!offset!of!–2!
means!back!up!two!positions!from!the!end!of!the!array.!Because!a!length!is!not!
specified,!the!array_splice()!function!will!copy!the!last!two!elements,!
"Christian"!and!"Jerry",!from!the!array!and!assign!them!to!$good_guys.
4
For!output!of!this!example,!see!Figure!8.52.
Figure 8.52. The array_slice() function. Output from Example 8.43.

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
8.2.4. Combining and Merging Arrays
The array_combine() Function
The array_combine() function returns an array made up of keys and values. The keys of the new array are the
made up of the values from the first array and the values associated with the new keys are made up of the values from
the second array (PHP 5). The function returns FALSE if there are an unequal number of values in either of the arrays

used as arguments.
Format
array array_combine ( array keys, array values )
!
Example:
$titles=array("President", "Programmer", "Accountant"); $names=array("Bill
McClintock", "Pearl White", "Barry Buck"); $new_array = array_combine( $titles,
$names); // Returns: "President =>"Bill McClintock, "Programmer"=>"Pearl //
White", "Accountant"=>"Barry Buck"

Example 8.44.
<html>
<head><title>Combining Arrays</title></head>
<body bgcolor="lightblue">
<h3>Combining Arrays</h3>
<pre>
<?php
1 $abbrev=array('CA', 'MT', 'VA');
2 $states=array('California','Montana','Virginia');
echo 'After combining $abbrev and $states',"<br />";
3 $combined=array_combine($abbrev, $states);
4 print_r($combined);
?>
<pre>
</body>
</html>
Explanation
1
An!numeric!array!called!$abbrev!is!assigned!three!string!values.
2

An!numeric!array!called!$states!is!assigned!three!string!values.
3
The!array_combine()!function!combines!the!two!arrays!so!that!the!values!in!
the!first!array!$abbrev!become!the!keys!corresponding!to!the!values!in!the!
second!array,!$states.!A!new!array!called!$combined,!an!associative!array!of!
key–value!pairs,!is!returned.
4
The!combined!array!is!printed.!The!keys!are!made!up!of!the!first!array,!$abbrev,!
and!the!values!from!the!second!array,!$states.!See!Figure!8.53!for!the!output.






Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.53. Combining arrays with keys and values. Output from Example 8.44.
!
The array_merge() Function
The array_merge() function joins two or more arrays together to return a single array. The values of one array are
appended to the end of the previous array.
Format
array array_merge ( array array1 [, array array2 [, array ]] )
!
Example:
$newarray=array_merge($array1, $array2); // Returns one array
If array elements have the same keys, then the key of the first array will be overwritten by the key of the next one. If,
however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If only one array is given and the array is numerically indexed, the keys get reindexed in order.
Merging Numerically Indexed Arrays

Example 8.45 demonstrates the merging of numerically indexed arrays using the array_merge() function.
Example 8.45.
<html>
<head><title>Merging Arrays</title></head>
<body bgcolor="lightblue">
<h3>Merging Arrays</h3>
<pre>
<?php
1 $primary=array('red', 'blue', 'yellow');
echo '$primary=array("red", "blue", "yellow")',"<br />";
2 $secondary=array('orange','purple','green');
echo '$secondary=array("orange","purple","green")',"<br
/>";
echo 'After merging $primary and $secondary',"<br />";
3 $merged=array_merge($primary, $secondary);
print_r($merged);
?>
<pre> </body> </html>
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Explanation
1
A!numeric!array,!called!$primary,!is!initialized.
2
A!second!numeric!array,!called!$secondary,!is!initialized!with!three!values.
3
The!array_merge()!function!appends!the!second!array!to!the!first!one.!The!index!values!
of!the!second!array!are!incremented!in!the!order!in!which!they!appear!in!the!new!
merged!array.
4
The!merged!arrays!are!shown!in!Figure!8.54.

!
Figure 8.54. Merging two arrays. Output from Example 8.45.
!

Merging Associative Arrays
Example 8.46 demonstrates merging associative arrays and removing duplicate keys.

Example 8.46.
<body bgcolor="lightblue">
<h3>Merging Associative Arrays</h3>
<pre>
<?php
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
1 $cyclewear1=array('item'=>'jersey', 'color'=>'blue',

'type'=> 'hooded');
2 $cyclewear2=array('size'=>'large','color'=>'white',

'cost'=>'145');
echo 'After merging $cyclewear1 and $cyclewear2',"<br />";
3 $merged=array_merge($cyclewear1, $cyclewear2);
4 print_r($merged);
?>
</pre>
</body>
</html>
Explanation
1
An!associative!array!is!initialized!with!key–value!pairs.
2

This!associative!array!has!a!'color'!key,!and!so!does!the!first!one.!When!they!are!
merged,!the!value!of!the!'color'!key!in!the!first!array!will!be!overwritten!by!the!value!
in!the!second!array.
3
The!second!array,!$cyclewear2,!is!appended!to!the!first!array,!$cyclewear1.!If!the!first!
array!and!the!second!array!have!duplicate!keys,!the!duplicate!keys!in! t he!first!array!are!
overwritten.
4
The!output!is!printed!as!shown!in!Figure!8.55.
Figure 8.55. Merging associative arrays. Output from Example 8.46.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The array_merge_recursive() Function
The array_merge_recursive() function merges two or more arrays recursively.
array_merge_recursive() merges the elements of one or more arrays together so that the values of one are
appended to the end of the previous one. It returns the resulting array.
Format
array array_merge_recursive ( array array1 [, array ] )

If you have two associative arrays being merged and their keys are the same but their values are different, the
array_merge_recursive() function will combine the values of both arrays into another array as shown in
Example 8.47.
If the arrays have the same numeric key, the later value will not overwrite the original value, but it will be appended.
Example 8.47.
!!!<head><title>Merging Associative Arrays</title></head>
<body bgcolor="lightblue">
<h3>Merging Associative Arrays</h3>
<pre>
<?php
1 $cyclewear1=array('item'=>'jersey', 'color'=>'blue',

'type'=> 'hooded');
2 $cyclewear2=array('size'=>'large','color'=>'white',
'cost'=>'145');
echo 'After merging $cyclewear1 and $cyclewear2',"<br />";
3 $merged=array_merge_recursive($cyclewear1, $cyclewear2);
4 print_r($merged);
?>
</pre>
</body>
</html>

Explanation
1
The!associative!array,!$cyclewear1,!contains!key–value!pairs!describing!an!item!called!
"jersey".
2
The!associative!array,!$cyclewear2,!contains!more!descriptive!key–value!pairs,!and!also!
has!a!'color'!key,!but!with!a!different!value.
3
The!array_merge_recursive()!function!merges!the!two!arrays!and!where!the!key!is!the!
same,!creates!an!array!of!values.!The!'color'!key!now!consists!of!an!array!of!colors,!
'blue'!and!'white'.
4
After!merging!two!arrays!recursively,!the!new!array!returned!from!
array_merge_recursive()!is!printed.!See!Figure!8.56.
!







Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.56. Merging keys and values. Output from Example 8.47.
!
8.2.5. Array Operators
The array operators used to manipulate arrays are listed in Table 8.10. These are the same operators we discussed in
Chapter 5, “Operators,” but they are now applied to arrays rather than strings and numbers.
Table 8.10. Array Operators
Operator
Function
Meaning
$a + $b
Union
Union!of!$a!and!$b
$a == $b
Equality
TRUE!if!$a!and!$b!have!the!same!key–value!pairs
$a ===
$b
Identity
TRUE!if!$a!and!$b!have!the!same!key–value!pairs!in!the!same!order!
and!of!the!same!types
$a != $b
Inequality
TRUE!if!$a!is!not!equal!to!$b
$a <> $b
Inequality
TRUE!if!$a!is!not!equal!to!$b
$a !==

$b
Nonidentity
TRUE!if!$a!is!not!identical!to!$b
!

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The Union Operator
The union operator joins two arrays: The array on the right side of the operator is joined to the array on the left side of
the operator. If any of the keys are the same, the keys on the left side of the array will not be overwritten. The union
operator is demonstrated in Example 8.48. The resulting arrays are shown in Figure 8.57.
Example 8.48.
<html>
<head><title>Union</title></head>
<body bgcolor="lightgreen">
<b>
<pre>
<?php
1 $colors=array('R'=>'red','G'=>'green','B'=>'blue');
2 $shades=array('G'=>'gray','BL'=>'black','W'=>'white');
/* two keys are the same */
3 $combo = $colors + $shades;// Join $shades to $colors
print_r($combo) . "<p>";
4 print_r($ shades + $colors);// Now join $colors to $shades
?>
</pre>
</b>
</body>
</html>
Explanation
1

The!array!called!$colors!is!assigned!key–value!pairs.
2
The!array!called!$shades!is!assigned!key–value!pairs.!The!key!'G'!is!common!
to!both!arrays!but!has!different!values.
3
The!union!operator!joins!the!two!arrays!together.!Both!arrays!have!a!'G'!key.!
The!values!of!the!array!on!the!left,!$colors,!will!not!be!overwritten!by!the!
values!of!the!keys!on!the!right.!See!Figure!8.57.
4
By!putting!$shades!on!the!left!side!of!the!+!operator,!the!value!of!its!'G'!key,!
'gray'!will!not!be!overwritten.


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 8.57. The union operator. Output from Example 8.48.
!
!
The Equality and Identical Operators
When using the equality operator to compare two arrays, if both keys and values have the same value, they are equal,
but the order and data type does not matter. To be identical, both the keys and values must be of the same data type,
same value, and in the same order. See Example 8.49.
Example 8.49.
Code!View:!
<html>
<head><title>Equality and Identity</title></head>
<body bgcolor="lightgreen">
<font face="arial" size='+1'>
<?php
1 $pets=array('dog', 'cat', 'bird');
2 $animals=array(1=>'cat',0 =>'dog', "2" => 'bird');

3 if ($pets == $animals){ // key-value pairs are equal
echo "\$pets and \$animals are equal.<br />";
}
else{
echo "\$pets and \$animals are not equal.<br />";
}
4 if ($pets === $animals){ /* key-value pairs must be in the
same
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

order and keys are of the same type */
echo "\$pets and \$animals are identical.<br />";
}
else{
5 echo "\$pets and \$animals are not identical.<br />";
}
6 $pets=array('dog','cat', 'bird');
// Reorder key-values
7 $animals=array(0=>'dog', 1=>'cat', 2=> 'bird');
8 if ($pets === $animals){
echo "Now \$pets and \$animals are identical.<br />";
}
?>
</body>
</html>
Explanation
1
The!array!called!$pets!is!assigned!three!values.!The!index!values!of!0,!1,!and!2!are!
assigned!automatically!if!not!specified.
2,!

3
The!array!called!$animals!is!assigned!three!values.!The!index!values!of!0,!1,!and!2!are!
assigned!to!each!of!the!elements,!but!the!elements!are!arranged!in!a!different!order.!
When!checking!for!equality,!as!long!as!the!keys!and!values!are!equal,!then!the!arrays!
are!equal.
4
When!testing!for!“identical,”!the!keys!and!values!not!only!have!to!be!equal,!but!they!
must!be!in!the!same!order.
5
This!line!is!executed!because!the!“identical”!test!failed!on!line!4.
6
The!array!called!$pets!is!assigned!three!values.!The!index!values!of!0,!1,!and!2!are!
assigned!automatically!if!not!specified.
7
The!$animals!array!is!assigned!numeric!indexes!and!values!that!are!in!the!same!order!
and!contain!the!same!values!as!the!$pets!array!on!line!6.!Even!though!they!look!
different,!the!array!elements!in!the!$pets!array!are!set!to!start!at!index!0!by!default.
8
The!$pets!array!is!identical!to!the!$animals!array;!that!is,!the!keys!and!values!are!the!
same!and!they!are!in!the!same!order,!then!the!expression!is!true!and!the!output!in!
Figure!8.58!will!be!printed.
!







Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Figure 8.58. Equal or identical? Output from Example 8.49.


8.2.6. More Array Functions
PHP 4 introduced more than 30 functions that allow you to manipulate an array in numerous ways. Table 8.11 lists of
most of the built-in array functions, many of which we described in detail in this chapter. See the PHP manual for a
complete list.
Table 8.11. The Most Common Array Functions
Function
What+It+Does
Creating!Arrays
array()
Creates!an!array!(see!page!252).
array_fill()
Declares!and!populates!an!array!(see!p a ge!255).
range()
Creates!an!array!starting!from!a!low!to!high!value!(see!page!
253).
Printing!Arrays
print_r()
Displays!both!keys/indexes!and!values!of!an!array!(see!page!
262).
var_dump()
Displays!an!array’s!size,!keys/indexes,!val u es,!and!length!(see!
page!265).
Merging!or!Combining!Arrays
array_combine()
Combines!two!arrays.!The!first!array!consists!of!elements!that!
will!serve!as!keys,!and!elements!of!the!second!array!will!serve!
as!values!for!the!returned!associative!array!(see!page!322).

array_merge()
Merges!one!or!more!arrays!(see!page!323).
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 8.11. The Most Common Array Functions
Function
What+It+Does
array_merge_recursive()
Merges!two!or!more!arrays!recursively!(see!page!326).
Arrays!and!Strings
explode()
Splits!up!a!string!by!a!specified!delimiter!and!creates!and!
array!of!strings!(see!page!276).
implode()
Glues!the!elements!of!an!array!together!by!some!delimiter!and!
creates!a!string!(see!page!276).
join()
Same!as!implode().
split()
Splits!a!string!into!an!array!by!a!delimiter!expressed!as!a!
regular!expression!(see!also!preg_split!on!page!510).
spliti()
Same!as!split,!but!case!insensitive.
Checking!for!Existence!of!an!Array,!Key,!or!Value
array_key_exists()
Checks!if!a!given!key!or!index!exists!in!an!array!(see!page!
274).
in_array()
Checks!if!a!value!exists!in!an!array!(see! page!274).
is_array()
Checks!if!the!variable!is!an!array!(see!pag e!274).

Extracting!Array!Keys!and!Values
array_keys()
Returns!all!the!keys!of!an!array!(see!page!281).
array_key_exists()
Checks!if!the!given!key!or!index!exists!in!the! array!(see!page!
274).
array_sum()
Calculates!the!sum!of!values!in!an!array.
array_values()
Returns!all!the!values!of!an!array!(see!page!283).
each()
Returns!the!current!key!and!value!pair!from!an!array!and!
advances!the!array!cursor!(see!page!284).
extract()
Extracts!values!from!an!array!and!creates!variables!of!the!
same!name!(see!page!288).
key()
Fetches!a!key!from!an!associative!array.
list()
Extracts!values!from!an!array!and!creates!user_defined!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×