19
arraypowerset
array_power_set
SYNOPSIS
array_power_set($arr)
DESCRIPTION
array_power_set
returns an array of all the different arrays which can be built with none, all or some of the elements of $arr
.
If $arr
is empty, array_power_set
returns an array containing an empty array.
EXAMPLE
php > require 'library/dump.php';
php > require 'library/arraypowerset.php';
php > $arr=array(1, 2, 3);
php > dump(array_power_set($arr));
array(8) {
[0] => array(0) {
}
[1] => array(1) {
[0] => int(1)
}
[2] => array(1) {
[0] => int(2)
}
[3] => array(2) {
[0] => int(2)
[1] => int(1)
}
[4] => array(1) {
[0] => int(3)
}
[5] => array(2) {
[0] => int(3)
[1] => int(1)
}
[6] => array(2) {
[0] => int(3)
[1] => int(2)
}
[7] => array(3) {
[0] => int(3)
[1] => int(2)
[2] => int(1)
}
}
arraypowerset(array(1,2,3))
returns array(array(), array(1), array(2), array(3), array(1, 2), array(1, 3), array(2, 3), array(1, 2, 3))
.
CODE
- function array_power_set($arr) {
- $r = array(array( ));
- foreach ($arr as $e) {
- foreach ($r as $c) {
- array_push($r, array_merge(array($e), $c));
- }
- }
- return $r;
- }
Comments