Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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