Skip to Content
Course content

90: array_merge and array_combine

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I'm currently working on a feature for a blog platform where I need to handle post tags. The goal is to take a set of "mandatory" tags (defined by the admin) and combine them with the tags the author chose. It sounds simple, but PHP's way of handling array combinations can be a bit slippery if you aren't paying attention to the keys.

The additive operator trap

My first instinct was to just use the plus operator. I've seen people do it, and it feels intuitive. Let's see what happens:

$mandatoryTags = ['Programming', 'WebDev'];
$userTags = ['PHP', 'Backend'];

$allTags = $mandatoryTags + $userTags;
print_r($allTags);

At first glance, this looks fine. I get both sets of tags. But then I tried it with a different set of data where the user tags were somehow indexed differently, or I tried to merge them in reverse. I quickly realized that the + operator doesn't actually "merge" in the way most people expect—it's a union. If a key exists in the first array, the second array's value for that key is simply ignored. Since these are indexed arrays, they both start at key 0. The + operator sees key 0 in $mandatoryTags and decides it doesn't need key 0 from $userTags.

That's a recipe for lost data. This is where array_merge() comes in.

Letting array_merge handle the heavy lifting

I swapped out the plus sign for the function call, and the behavior changed immediately:

$mandatoryTags = ['Programming', 'WebDev'];
$userTags = ['PHP', 'Backend'];

$allTags = array_merge($mandatoryTags, $userTags);
print_r($allTags);
// Output: [0 => 'Programming', 1 => 'WebDev', 2 => 'PHP', 3 => 'Backend']

Now it's actually appending the elements and re-indexing them. This is exactly what I wanted for a list of tags. But wait—what happens if I'm merging associative arrays, like user settings? I tried this:

$defaultSettings = ['theme' => 'light', 'notifications' => true];
$userSettings = ['theme' => 'dark'];

$finalSettings = array_merge($defaultSettings, $userSettings);
print_r($finalSettings);
// Output: ['theme' => 'dark', 'notifications' => true]

Notice how 'theme' was overwritten? With string keys, array_merge doesn't append; it overwrites. This is actually a superpower for things like configuration files where you want user preferences to override system defaults.

Pairing separate lists with array_combine

Now, I've hit a different problem. My database is returning two separate arrays for a list of categories: one array of IDs and one array of Category Names. They are perfectly aligned by index, but they are useless to me as two separate lists. I need them as a single associative array where the ID is the key.

I could write a foreach loop, but that feels like overkill for this. I remember there's a specific tool for this "zipping" action: array_combine().

$categoryIds = [10, 22, 45];
$categoryNames = ['News', 'Tutorials', 'Reviews'];

$categoryMap = array_combine($categoryIds, $categoryNames);
print_r($categoryMap);
/* 
Output: 
Array (
    [10] => News
    [22] => Tutorials
    [45] => Reviews
)
*/

It's clean and readable. One thing I noticed while testing this: if the two arrays aren't the exact same length, array_combine will throw a ValueError. It's strict. If you're pulling this data from an external API, you'd probably want to wrap this in a check to ensure count($categoryIds) === count($categoryNames) before attempting the combine.




📋 Practical Task

Build a User Profile Data Mapper

You are receiving raw data from two different legacy API endpoints. One endpoint provides a list of attribute keys, and the other provides the corresponding values for a specific user. Additionally, you have a set of default profile attributes that must be applied if the user hasn't specified them.

Your task:

  • Create an array $keys = ['first_name', 'last_name', 'timezone', 'language'].
  • Create an array $values = ['Jane', 'Doe', 'UTC', 'English'].
  • Use array_combine to merge these into a $userProfile associative array.
  • Create a $defaults array containing 'theme' => 'light' and 'language' => 'Spanish'.
  • Use array_merge to combine the $defaults and the $userProfile so that the user's actual data overrides the defaults.
  • Print the final resulting array to the screen.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.