Combinations in PHP

Eventually we may need to get all possible combinations between some elements. For example let’s say we have 3 elements. A, B and C. Now we want to get all the possible combinations of these elements making groups of two. The result is 3 combinations:

AB
AC
BC

It looks very straightforward, however a function like this doesn’t exist in PHP. So you may find the following code useful, it has been implemented extending the PHP’s Iterator Interface.

class Combinations implements Iterator
{
    protected $c = null;
    protected $s = null;
    protected $n = 0;
    protected $k = 0;
    protected $pos = 0;

    function __construct($s, $k) {
        if(is_array($s)) {
            $this->s = array_values($s);
            $this->n = count($this->s);
        } else {
            $this->s = (string) $s;
            $this->n = strlen($this->s);
        }
        $this->k = $k;
        $this->rewind();
    }
    function key() {
        return $this->pos;
    }
    function current() {
        $r = array();
        for($i = 0; $i < $this->k; $i++)
            $r[] = $this->s[$this->c[$i]];
        return is_array($this->s) ? $r : implode('', $r);
    }
    function next() {
        if($this->_next())
            $this->pos++;
        else
            $this->pos = -1;
    }
    function rewind() {
        $this->c = range(0, $this->k);
        $this->pos = 0;
    }
    function valid() {
        return $this->pos >= 0;
    }
    //
    protected function _next() {
        $i = $this->k - 1;
        while ($i >= 0 && $this->c[$i] == $this->n - $this->k + $i)
            $i--;
        if($i < 0)
            return false;
        $this->c[$i]++;
        while($i++ < $this->k - 1)
            $this->c[$i] = $this->c[$i - 1] + 1;
        return true;
    }
}

How does it work?

Create an instance of the object Combinations using a string/array whit all elements to combine as the first param and the group size as the second.

Get combinations using array

For getting all the possible combinations using the values of an array:

foreach(new Combinations(array('a','b','c'), 2) as $substring){
    var_dump($substring);
}
//Result:
//array (size=2)
//  0 => string 'a' (length=1)
//  1 => string 'b' (length=1)
//array (size=2)
//  0 => string 'a' (length=1)
//  1 => string 'c' (length=1)
//array (size=2)
//  0 => string 'b' (length=1)
//  1 => string 'c' (length=1)

Get combinations using string

For getting all the possible combinations between the values of a string:

foreach(new Combinations('abc', 2) as $substring){
    echo($substring).'<br>';
}
//Result:
//ab
//ac
//bc

Comments 1

Leave a Reply

Your email address will not be published. Required fields are marked *