9

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
  1. function array_power_set($arr) {
  2.     $r = array(array( ));
  3.  
  4.     foreach ($arr as $e) {
  5.         foreach ($r as $c) {
  6.             array_push($r, array_merge(array($e), $c));
  7.         }
  8.     }
  9.  
  10.     return $r;
  11. }

Comments

To add a comment, click here.