- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
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]; } ?>