Merging Arrays with PHP

Merging arrays with PHPI love working with arrays. They can be used to save a whole heap of data. Sometimes I need to merge two or more arrays together to make one larger array. This is a very simple process within PHP:

<?php
 $array_1 = array("Orange", "Red", "Blue");
 $array_2 = array("Green", "Purple", "Yellow", "Blue");
 $array_all = array_merge($array_1, $array_2);
 echo "<pre>";
 print_r($array_all);
 echo "</pre>";
 ?>

This will now parse to the browser as:

Array
(
    [0] => Orange
    [1] => Red
    [2] => Blue
    [3] => Green
    [4] => Purple
    [5] => Yellow
    [6] => Blue
)

You might want to also consider using array_unique to remove duplicates:

$array_all = array_unique($array_all);

How about sorting the array:

sort($array_all);

We now have a nice clean array:

Array
(
    [0] => Blue
    [1] => Green
    [2] => Orange
    [3] => Purple
    [4] => Red
    [5] => Yellow
)

Putting merging arrays into a function

I’m now going to put the steps for merging arrays into a simple PHP function:

<?php
 $array_1 = array("Orange", "Red", "Blue");
 $array_2 = array("Green", "Purple", "Yellow", "Blue");

 function merge_n_tidy($array_1, $array_2) {
 $array_all = array_merge($array_1, $array_2);
 $array_all = array_unique($array_all);
 sort($array_all);
 return $array_all;
 }

 echo "<pre>";
 print_r(merge_n_tidy($array_1, $array_2));
 echo "</pre>";
 ?>

Can array_merge be used within multi-dimensional arrays?

Works in just the same way. However, you can’t use ‘array_unique’ with multi-dimensional arrays.

<?php
 $array_1[] = array("Orange", "Red", "Blue");
 $array_1[] = array("Brown", "Black", "Grey");
 $array_2[] = array("Green", "Purple", "Yellow", "Blue");
 $array_2[] = array("White", "Cyan", "Magenta", "Turquiose");
 ?>

 <?php
 function merge_n_tidy($array_1, $array_2) {
 $array_all = array_merge($array_1, $array_2);
 sort($array_all);
 return $array_all;
 }

 echo "<pre>";
 print_r(merge_n_tidy($array_1, $array_2));
 echo "</pre>";
 ?>

This will parse as:

Array
(
    [0] => Array
        (
            [0] => Brown
            [1] => Black
            [2] => Grey
        )

    [1] => Array
        (
            [0] => Orange
            [1] => Red
            [2] => Blue
        )

    [2] => Array
        (
            [0] => Green
            [1] => Purple
            [2] => Yellow
            [3] => Blue
        )

    [3] => Array
        (
            [0] => White
            [1] => Cyan
            [2] => Magenta
            [3] => Turquoise
        )

)

As always, enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *