Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

4.25. Finding All Permutations of an Array

Problem

You have an array of elements and want to compute all the different ways they can be ordered.

Solution

Use one of the two permutation algorithms discussed next.

Discussion

The pc_permute() function shown in Example 4-6 is a PHP modification of a basic recursive function.

Example 4-6. pc_permute( )

function pc_permute($items, $perms = array( )) {
    if (empty($items)) { 
        print join(' ', $perms) . "\n";
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}

For example:

pc_permute(split(' ', 'she sells seashells'));
she sells seashells
               she seashells sells
               sells she seashells
               sells seashells she
               seashells she sells
               seashells sells she

However, while this recursion is elegant, it’s inefficient, because it’s making copies all over the place. Also, it’s not easy to modify the function to return the values instead of printing them out without resorting to a global variable.

The pc_next_permutation( ) function shown in Example 4-7, however, is a little slicker. It combines an idea of Mark-Jason Dominus from Perl Cookbook by Tom Christianson and Nathan Torkington (O’Reilly) with an algorithm from Edsger Dijkstra’s classic text A Discipline of Programming (Prentice-Hall).

Example 4-7. pc_next_permutation( )

function pc_next_permutation($p, $size) { // slide down the array looking for where we're ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata