Combining arrays in PHP

html-code

If you need to combine two arrays in PHP, you first thought might be to use the + operator. However, this is unlikely to do what you want it to to. If we look at the following example, you might expect it to output an array with all three elements.

<?php

$listA = ['banana'];
$listB = ['apple', 'pear'];
$listC = $listA + $listB;

var_dump($listC);

However, what you will actually get back is an array containing two elements: banana and pear. This is because when you use the + operator in PHP it combines it using array keys. Even though these are non-indexed arrays, PHP looks at them like this:

[0 => 'banana']
[0 => 'apple', 1 => 'pear']

Therefore when you add them together, it combines the keys, taking the earliest. In this case, to get the result you want, you want to use the array_merge function. For other scenarios, PHP has a range of different functions to combine arrays in different ways.

Timeline

Newsletter

Don't have time to check my blog? Get a weekly email with all the new posts. This is my personal blog, so obviously it is 100% spam free.

Metadata

Tags: , ,

This entry was posted on Monday, June 6th, 2016 at 11:05 am and is filed under Programming. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.