11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 5 • ARRAYSwww.it-ebooks.infoMerging ArraysThe array_merge() function merges arrays together, returning a single, unified array. The resulting arraywill begin with the first input array parameter, appending each subsequent array parameter in the orderof 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 pairwill overwrite the previously existing entry. This behavior does not hold true for numerical keys, inwhich case the key/value pair will be appended to the array. An example follows:$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 ArraysThe array_merge_recursive() function operates identically to array_merge(), joining two or more arraystogether to form a single, unified array. The difference between the two functions lies in the way that thisfunction behaves when a string key located in one of the input arrays already exists within the resultingarray. Note that array_merge() will simply overwrite the preexisting key/value pair, replacing it with theone found in the current input array, while array_merge_recursive() will instead merge the valuestogether, forming a new array with the preexisting key as its name. Its prototype follows:array array_merge_recursive(array array1, array array2 [, array arrayN])An example follows:$class1 = array("John" => 100, "James" => 85);$class2 = array("Micky" => 78, "John" => 45);$classScores = array_merge_recursive($class1, $class2);print_r($classScores);This returns the following:Array ( [John] => Array ( [0] => 100 [1] => 45 ) [James] => 85 [Micky] => 78 )Note that the key John now points to a numerically indexed array consisting of two scores.126

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!