I am trying to generate all combinations from an array, and I have the array given below,
$myArray = array('A','B','C');
What is the simplest way to generate combinations like,
Array
(
[0] => Array
(
[0] => A
[1] => B
)
[1] => Array
(
[0] => B
[1] => C
)
[2] => Array
(
[0] => A
[1] => C
)
[3] => Array
(
[0] => A
[1] => B
[2] => C
)
)
Thanks in advance
<?php
echo "<table>";
echo "<thead>";
echo "<tr><th>Chemical One</th><th>Chemical two</th></tr>";
echo "</thead>";
echo "<tbody>";
$chemical=array('c1','c2','c3','c4');
$count_chem=count($chemical);
for ($i=0; $i <= $count_chem; $i++) {
for ($j=$i+1; $j < $count_chem; $j++) {
echo "<tr>";
echo "<td>".$chemical[$i]."</td>";
echo "<td>".$chemical[$j]."</td>";
echo "<tr>";
}
}
echo "</tbody></table>";
?>
the question is similar Click How to compare one element from same table to another element to already asked.
Well, the simplest way is by just appending a new Subarray at the end:
$myarray = array()
$myarray[] = array('A', 'B');
$myarray[] = array('C', 'D');
You can use as many array dimensions as you want or need. But it becomes soon unreadable and/or unmanageable. Consider to use classes instead, to show other programmers what you meant with your data structure.
As you said combining arrays, you could also use array_merge
it depends a bit on the specific situation, which option is better.
EDIT The following code gives the result that you want (not just for array with 3 element like the code before the edited asnwer) but i doubt it is the best possible way, but since no one provided an answer you can use this until you find a better way
$myArray = array('A','B','C','D');
$result=array_combinations($myArray);
print_r($result);
function array_combinations($array){
$result=[];
for ($i=0;$i<count($array)-1;$i++) {
$result=array_merge($result,combinations(array_slice($array,$i)));
}
return $result;
}
function combinations($array){
//get all the possible combinations no dublicates
$combinations=[];
$combinations[]=$array;
for($i=1;$i<count($array);$i++){
$tmp=$array;
unset($tmp[$i]);
$tmp=array_values($tmp);//fix the indexes after unset
if(count($tmp)<2){
break;
}
$combinations[]=$tmp;
}
return $combinations;
}
results
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
[3] => D
)
[1] => Array
(
[0] => A
[1] => C
[2] => D
)
[2] => Array
(
[0] => A
[1] => B
[2] => D
)
[3] => Array
(
[0] => A
[1] => B
[2] => C
)
[4] => Array
(
[0] => B
[1] => C
[2] => D
)
[5] => Array
(
[0] => B
[1] => D
)
[6] => Array
(
[0] => B
[1] => C
)
[7] => Array
(
[0] => C
[1] => D
)
)
you can find a demo here