Manipulating Arrays

You can now populate arrays and access their elements, but PHP has functions to help you do much more than that with arrays. If you’re used to Perl, you’ll find some of these eerily familiar!

Joining Two Arrays with array_merge()

array_merge() accepts two or more arrays and returns a merged array combining all their elements. In the following example, we create two arrays, joining the second to the first, and loop through the resultant third array:

$first = array("a", "b", "c");
$second = array(1,2,3);
$third = array_merge( $first, $second );

foreach ( $third as $val ) {
  print "$val<br />";
}

The $third array contains copies of all the elements of both the $first and $second arrays. The foreach statement prints this combined ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.