How to generate all possible X combinations of N characters in PHP

1 Answer

0 votes
<?php

function create_combinations($chars, $size, $combinations = array()) {
    if (empty($combinations)) {
        $combinations = $chars;
    }

    if ($size == 1) {
        return $combinations;
    }

    $new_combinations = array();

    foreach ($combinations as $combination_ch) {
        foreach ($chars as $ch) {
            $new_combinations[] = $combination_ch . $ch;
        }
    }

    return create_combinations($chars, $size - 1, $new_combinations);
}

$Nchars = array('a', 'b', 'c', 'd');
$X = 2;

$arr = create_combinations($Nchars, $X);

print_r($arr);




/*
run:

Array
(
    [0] => aa
    [1] => ab
    [2] => ac
    [3] => ad
    [4] => ba
    [5] => bb
    [6] => bc
    [7] => bd
    [8] => ca
    [9] => cb
    [10] => cc
    [11] => cd
    [12] => da
    [13] => db
    [14] => dc
    [15] => dd
)

*/


?>

 



answered Oct 2, 2021 by avibootz
...