PHP – All Combinations Between Array Elements

PHP – All Combinations Between Array Elements

OK, this is what I need to solve. Given an array of the following elements:
$array1 = array(1, 2);
$array2 = array(3);
$array3 = array(4, 5);
I want to get the following combinations:
array(1, 3, 4)
array(1, 3, 5)
array(2, 3, 4)
array(2, 3, 5)
It is quite obvious that I will need a recursive function to do this, but it is not straightforward to start writing the function straightaway. With the hope that someone else might have already got such a function to do the task, I started googling and found a perfect post from Amoeba However, his function only prints out combinations with strings, I have modified it slightly so that it returns arrays for my own purpose, and without using of global variables:
public static function getArrayCombinations($arr, &$final, &$codes = array(), &$pos = 0)
    if(count($arr)) {
        for($i=0; $i

It works perfectly fine and is exactly what I am looking for. Thanks for the post and it saved me lots of time to write this recursive function.

Leave a Reply

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

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!