Working Out Combinations of a Multidimensional Array in PHP

Occasionally you may wish to work out all the possible combinations of array elements and have probably trawled the internet looking for solutions and have come across many sites giving details of how to work out all the possible permutations… This is NOT permutations, but simple combinations:

function workOutCombinations ($data, &$all = array(), $group = array(), $val = null, $i = 0) {
    if (isset($val)) {
        array_push($group, $val);

    if ($i >= count($data)) {
        array_push($all, $group);
    } else {
        foreach ($data[$i] as $v) {
            workOutCombinations($data, $all, $group, $v, $i + 1);
    return $all;

$ar[0] = array('a', 'b', 'c');
$ar[1] = array('1', '2', '3');
$ar[2] = array('red', 'green', 'blue');
$ar[2] = array('cat', 'dog', 'fish');

$combos = workOutCombinations($ar);

PLEASE NOTE: This is not my solution. The code above is a tweak of the original found on without PHP whining about depricated pass-by-reference usage.


Leave a Reply

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