Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Created February 1, 2013 03:13
Show Gist options
  • Save cecilemuller/4688876 to your computer and use it in GitHub Desktop.
Save cecilemuller/4688876 to your computer and use it in GitHub Desktop.
PHP: Get all combinations of multiple arrays (preserves keys)
<?php
function get_combinations($arrays) {
$result = array(array());
foreach ($arrays as $property => $property_values) {
$tmp = array();
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(
array(
'item1' => array('A', 'B'),
'item2' => array('C', 'D'),
'item3' => array('E', 'F'),
)
);
var_dump($combinations);
?>
array (size=8)
0 =>
array (size=3)
'item1' => string 'A' (length=1)
'item2' => string 'C' (length=1)
'item3' => string 'E' (length=1)
1 =>
array (size=3)
'item1' => string 'A' (length=1)
'item2' => string 'C' (length=1)
'item3' => string 'F' (length=1)
2 =>
array (size=3)
'item1' => string 'A' (length=1)
'item2' => string 'D' (length=1)
'item3' => string 'E' (length=1)
3 =>
array (size=3)
'item1' => string 'A' (length=1)
'item2' => string 'D' (length=1)
'item3' => string 'F' (length=1)
4 =>
array (size=3)
'item1' => string 'B' (length=1)
'item2' => string 'C' (length=1)
'item3' => string 'E' (length=1)
5 =>
array (size=3)
'item1' => string 'B' (length=1)
'item2' => string 'C' (length=1)
'item3' => string 'F' (length=1)
6 =>
array (size=3)
'item1' => string 'B' (length=1)
'item2' => string 'D' (length=1)
'item3' => string 'E' (length=1)
7 =>
array (size=3)
'item1' => string 'B' (length=1)
'item2' => string 'D' (length=1)
'item3' => string 'F' (length=1)
@fofopp
Copy link

fofopp commented Nov 8, 2023

Thanks! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment