Prev | Current Page 222 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


Merging Arrays
The array_merge() function merges arrays together, returning a single, unified array.
The resulting array will begin with the first input array parameter, appending each
subsequent array parameter in the order of appearance. Its prototype follows:
array array_merge(array array1, array array2 [..., array arrayN])
If an input array contains a string key that already exists in the resulting array, that
key/value pair will overwrite the previously existing entry. This behavior does not
hold true for numerical keys, in which case the key/value pair will be appended to the
array. An example follows:
154 CHAPTER 5 ?–  ARRAYS
$face = array("J","Q","K","A");
$numbered = array("2","3","4","5","6","7","8","9");
$cards = array_merge($face, $numbered);
shuffle($cards);
print_r($cards);
This returns something along the lines of the following (your results will vary
because of the shuffle):
Array ( [0] => 8 [1] => 6 [2] => K [3] => Q [4] => 9 [5] => 5
[6] => 3 [7] => 2 [8] => 7 [9] => 4 [10] => A [11] => J )
Recursively Appending Arrays
The array_merge_recursive() function operates identically to array_merge(), joining
two or more arrays together to form a single, unified array. The difference between
the two functions lies in the way that this function behaves when a string key located in
one of the input arrays already exists within the resulting array.


Pages:
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234