From the course: PHP Tips, Tricks, and Techniques

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Merging arrays

Merging arrays

- [David Powers] Hi, I'm David Powers and welcome to this week's edition of PHP Tips, Tricks and Techniques designed to help you become a smarter, more productive PHP developer. Last time, I showed you how to generate all permutations of an array. It involved pulling apart an array and stitching it back together with array_merge. And that set me thinking about merging arrays in general. It's one of those aspects of PHP that doesn't always work how you might expect. So, it's useful to know what does happen. PHP handles associative arrays that use strings as keys differently than index arrays that use numeric keys. So, let's take associative arrays first. In this file, I've created two associative arrays: assoc1 and assoc2. Then I'm merging them using array_merge and inspecting the results using print_r. When arrays don't have any duplicate keys, the second array is simply appended to the first. But in this example, both arrays have a key called country. So, let's see what happens when…

Contents