Skip to content

Instantly share code, notes, and snippets.

@jakeasmith
Created June 21, 2012 21:25
Show Gist options
  • Save jakeasmith/2968618 to your computer and use it in GitHub Desktop.
Save jakeasmith/2968618 to your computer and use it in GitHub Desktop.
Build an array of strings with every possible variation of multiple other strings
<?php
$foo = array(
array(
'Black',
'White',
'Green'
),
array(
'Small',
'Medium',
'Large',
),
array(
'Auto',
'Manual'
)
);
function process_variations($types)
{
$variations = array();
$type = array_shift($types);
foreach($type as $string)
{
$variations[] = $string;
}
foreach($types as $type)
{
$original = $variations;
$variations = array();
foreach($type as $new)
{
foreach($original as $prefix)
{
$variations[] = $prefix . $new;
}
}
}
return $variations;
}
print_r(process_variations($foo));
// Returns:
// Array
// (
// [0] => BlackSmallAuto
// [1] => WhiteSmallAuto
// [2] => GreenSmallAuto
// [3] => BlackMediumAuto
// [4] => WhiteMediumAuto
// [5] => GreenMediumAuto
// [6] => BlackLargeAuto
// [7] => WhiteLargeAuto
// [8] => GreenLargeAuto
// [9] => BlackSmallManual
// [10] => WhiteSmallManual
// [11] => GreenSmallManual
// [12] => BlackMediumManual
// [13] => WhiteMediumManual
// [14] => GreenMediumManual
// [15] => BlackLargeManual
// [16] => WhiteLargeManual
// [17] => GreenLargeManual
// )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment