3.5 Merging Arrays


You want to append one array onto another and the array_push() function doesn't do the job.

Technique

Use PHP 4's array_merge() function to append one or more arrays:

 <?php $good_guys = array ("Gandalf", "Radagast", "Saruman"); $bad_guys  = array ("Nazgul", "Sauron", "Orcs"); $all_guys = array_merge ($good_guys, $bad_guys); ?> 

As a bit of syntactic sugar, you can also use the + sign to merge two or more arrays:

 <?php $places = array ("Lothlorien", "Orthanc", "Rivendell", "Hobbiton", "Bree"); $people = array ("Galadriel",  "Saruman", "Elrond",   "Frodo",    "Butterbee"); $both = $places + $people; ?> 

If you don't want to lose elements that are the same in both arrays, you can use the array_merge_recursive() function:

 <?php $good_guys = array ("Gandalf", "Radagast", "Saruman"); $bad_guys  = array ("Nazgul", "Sauron", "Orcs"); $fallen    = array ("Denethor", "Saruman"); $everybody = array_merge_recursive ($good_guys, $bad_guys, $fallen); ?> 

Comments

In Perl, you would use the push() function to merge two arrays together. (Arrays in Perl are automatically flattened when used in list context; thankfully, this is not so in PHP.) However, in PHP, using the array_push() function will give you a two-dimensional array:

 <?php $good_guys = array ("Gandalf","Radagast","Saruman"); $bad_guys  = array ("Nazgul","Sauron","Orcs"); $all_guys = array_push ($good_guys, $bad_guys); print $all_guys[3][1]; // prints Sauron ?> 

You can also merge two arrays using a loop (PHP 3 compatible):

 <?php for ($i = 0; $i < count ($ar2); $i++ ) {     $ar1[] = $ar2[$i]; } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net