20

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

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].