Prev | Current Page 223 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

array_merge() will
simply overwrite the preexisting key/value pair, replacing it with the one found in the
current input array. array_merge_recursive() will instead merge the values together,
forming a new array with the preexisting key as its name. Its prototype follows:
array array_merge_recursive(array array1, array array2 [, 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.
CHAPTER 5 ?–  ARRAYS 155
Combining Two Arrays
The array_combine() function produces a new array consisting of a submitted set of
keys and corresponding values. Its prototype follows:
array array_combine(array keys, array values)
Both input arrays must be of equal size, and neither can be empty. An example
follows:
$abbreviations = array("AL","AK","AZ","AR");
$states = array("Alabama","Alaska","Arizona","Arkansas");
$stateMap = array_combine($abbreviations,$states);
print_r($stateMap);
This returns the following:
Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona [AR] => Arkansas )
Slicing an Array
The array_slice() function returns a section of an array based on a provided starting
and ending offset value.


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