Skip to content

Instantly share code, notes, and snippets.

@cereal-s
Forked from cecilemuller/get_combinations.php
Last active August 26, 2019 08:47
Show Gist options
  • Save cereal-s/5c896a161c5e7af52e4b3afde4d27076 to your computer and use it in GitHub Desktop.
Save cereal-s/5c896a161c5e7af52e4b3afde4d27076 to your computer and use it in GitHub Desktop.
PHP: Get all combinations of multiple arrays (preserves keys)
<?php
function get_combinations($arrays) {
$result = [[]];
foreach ($arrays as $property => $property_values) {
$tmp = [];
foreach ($result as $result_item) {
foreach ($property_values as $property_value) {
$tmp[] = array_merge($result_item, array($property => $property_value));
}
}
$result = $tmp;
}
return $result;
}
$combinations = get_combinations(
[
'item1' => ['A', 'B'],
'item2' => ['C', 'D'],
'item3' => ['E', 'F'],
]
);
print_r($combinations); // 2*2*2 = 8
Array
(
[0] => Array
(
[item1] => A
[item2] => C
[item3] => E
)
[1] => Array
(
[item1] => A
[item2] => C
[item3] => F
)
[2] => Array
(
[item1] => A
[item2] => D
[item3] => E
)
[3] => Array
(
[item1] => A
[item2] => D
[item3] => F
)
[4] => Array
(
[item1] => B
[item2] => C
[item3] => E
)
[5] => Array
(
[item1] => B
[item2] => C
[item3] => F
)
[6] => Array
(
[item1] => B
[item2] => D
[item3] => E
)
[7] => Array
(
[item1] => B
[item2] => D
[item3] => F
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment