Skip to content

Instantly share code, notes, and snippets.

@zamaldev
Last active December 4, 2020 16:49
Show Gist options
  • Save zamaldev/8eca592d7b7a3720b3b19037d2f78819 to your computer and use it in GitHub Desktop.
Save zamaldev/8eca592d7b7a3720b3b19037d2f78819 to your computer and use it in GitHub Desktop.
Generation of all possible combinations of array elements
<?php
function getIndexCombinations($arValues): array {
$iProduct = 1;
foreach ($arValues as $arSubArray) $iProduct *= count($arSubArray);
$arIndexCombinations = [];
for ($i = 0; $i < $iProduct; $i++) {
$arIndices = [];
$iCount = 1;
for ($j = 0; $j < count($arValues); $j++) {
$arIndices[$j] = ($i / $iCount) % count($arValues[$j]);
$iCount *= count($arValues[$j]);
}
for ($j = 0; $j < count($arIndices); $j++) {
$arIndexCombinations[$i][$j] = $arIndices[$j];
}
}
return $arIndexCombinations;
}
// Example
$arValues = [['a','b'],[1,2,3],['A','B','C'],['I','K']];
$arCombinations = getIndexCombinations($arValues);
foreach ($arCombinations as $arLine) {
foreach ($arLine as $iSubArrayId => $iIndex) {
echo $arValues[$iSubArrayId][$iIndex];
}
echo PHP_EOL;
}
// If you have an associative array, you can change a bit code above, and gets the following function:
function getAssociativeIndexCombinations($arValues): array {
$iProduct = 1;
$arKeys = [];
foreach ($arValues as $sKey => $arSubArray) {
$iProduct *= count($arSubArray);
$arKeys[] = $sKey;
}
$arIndexCombinations = [];
for ($i = 0; $i < $iProduct; $i++) {
$arIndices = [];
$iCount = 1;
for ($j = 0; $j < count($arValues); $j++) {
$arIndices[$j] = ($i / $iCount) % count($arValues[$arKeys[$j]]);
$iCount *= count($arValues[$arKeys[$j]]);
}
for ($j = 0; $j < count($arIndices); $j++) {
$arIndexCombinations[$i][$arKeys[$j]] = $arIndices[$j];
}
}
return $arIndexCombinations;
}
// Example
$arValues = ['10' => ['a','b'], '11' => [1,2,3], '12' => ['A','B','C'], '13' => ['I','K']];
$arCombinations = getAssociativeIndexCombinations($arValues);
$arKeys = array_keys($arValues);
foreach ($arCombinations as $arLine) {
foreach ($arLine as $sKey => $iIndex) {
echo $arValues[$sKey][$iIndex];
}
echo PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment