Word Permutator Function

Give this function a phrase and it will return all of the permutations of the words that make up the phrase.

the function

<?php
function wordperms($phrase,$top='') {
	$output = array();
	
	if (is_array($phrase)) {
		$phrase_pieces = $phrase;
	}
	else {
		$phrase_pieces = explode(' ',$phrase);
	}
	$top_pieces = explode(' ',$top);
	foreach ($phrase_pieces as $piece) {
		if (!in_array($top.$piece,$output) && !in_array($piece,$top_pieces)) {
			$output[] = $top.$piece;
			$output = array_merge($output,wordperms($phrase_pieces,$top.$piece.' '));
		}
	}
	return $output;	
}
?>

example

<?php
// example
print_r(wordperms("three word phrase"));
/*
Array
(
    [0] => three
    [1] => three word
    [2] => three word phrase
    [3] => three phrase
    [4] => three phrase word
    [5] => word
    [6] => word three
    [7] => word three phrase
    [8] => word phrase
    [9] => word phrase three
    [10] => phrase
    [11] => phrase three
    [12] => phrase three word
    [13] => phrase word
    [14] => phrase word three
)
*/
?>

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <i> <strong> <cite> <em> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <css>, <diff>, <drupal5>, <html>, <javascript>, <php>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.