Hacking with PHP has been updated for PHP 7 - click here! >>

Chopping and changing arrays

array array_diff ( array array1, array array2 [, array ...])

array array_intersect ( array array1, array array2 [, array ...])

array array_merge ( array array1, array array2 [, array ...])

There are three key functions that handle the comparison of two arrays to create a new array, and they work in much the same way - they take a minimum of two arrays as parameters (we will call them $arr1 and $arr2), and return an array for a result.

The difference is that array_diff() returns a new array containing all the values of $arr1 that do not exist in $arr2, array_intersect() returns a new array containing all the values of $arr1 that do exist in $arr2, and array_merge() just combines the two arrays. These three functions work well as a team, and allow you to construct combined arrays out of individual arrays.

Here is an example with these three functions in action:

    $toppings1 = array("Pepperoni", "Cheese", "Anchovies", "Tomatoes");
    $toppings2 = array("Ham", "Cheese", "Peppers");
    $inttoppings = array_intersect($toppings1, $toppings2);
    $difftoppings = array_diff($toppings1, $toppings2);
    $bothtoppings = array_merge($toppings1, $toppings2);

As you can see, there are two arrays of pizza toppings, and they both share cheese as a value. Here is what that script outputs:

array(1) { [1]=> string(6) "Cheese" }
array(3) { [0]=> string(9) "Pepperoni" [2]=> string(9) "Anchovies" [3]=> string(8) "Tomatoes" }
array(7) { [0]=> string(9) "Pepperoni" [1]=> string(6) "Cheese" [2]=> string(9) "Anchovies" [3]=> string(8) "Tomatoes" [4]=> string(3) "Ham" [5]=> string(6) "Cheese" [6]=> string(7) "Peppers" }

Array_intersect(), if you recall, returns an array listing all values in array parameter one that are also in array parameter two, so this call in our example will put just one element, cheese, into $inttoppings. The call to array_diff() will place into $difftoppings all the values from $toppings1 that aren't in $toppings2, namely pepperoni, anchovies, and tomatoes.

Finally we have a call to array_merge(), which results in seven elements being placed into $bothtoppings: pepperoni, cheese, anchovies, tomatoes, peppers, ham, and cheese. As you can see, "cheese" is in there twice, so what you really need now is a way to strip out duplicate values.

Author's Note: The + operator in PHP is overloaded so that you can use it to merge arrays, eg $array3 = $array1 + $array2, but will ignore any key clashes, and so is quite confusing to use unless you have unique keys.


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Stripping out duplicate values >>

Previous chapter: Array-specific functions

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.