<?php
/*
This simple program lists all word or symbol permutations within a string.
AUTHOR : Jay Tanner - 2025
LANGUAGE : PHP v8.2.12
LICENSE : Public Domain
*/
ob_start();
// Define the program cookie name and set it to expire in 30 days.
// This cookie can be shared by other programs in the same common
// home folder together.
$CookieName = 'List_All_Word_Permutations_Within_a_Text_String';
$SetToExpireIn7Days = time() + 7*86400;
// Define script path and filename.
$_AUTHOR_ = 'Jay Tanner';
$_PROGRAM_VERSION_ = ''; $at = "at"; $UTC = "UTC";
$_SCRIPT_PATH_ = Filter_Input(INPUT_SERVER, 'SCRIPT_FILENAME');
$_RUN_ = Filter_Input(INPUT_POST, 'SCRIPT_NAME');
// Define internal document page title, HTML page heading text and revision date
$_INTERNAL_TITLE_ = "List All Word Permutations Within a Text String";
$_INTERFACE_TITLE_ = "<b style='font-size:16px;'>List All Word/Item Permutations Within a Text String</b><br><span style='font-size:12px;'><br></span>";
$_REVISION_DATE_ = $_PROGRAM_VERSION_ .'Revised: '. GMDate("l, F d, Y $at h:i:s A $UTC", FileMTime($_SCRIPT_PATH_));
// Define main TextArea text, background
// colors and HTML table cloumn span.
$TxColor = 'black';
$BgColor = 'white';
$ColSpan = 1;
$DLLink = '';
// Do this only if [COMPUTE] button was clicked.
$w = Filter_Input(INPUT_POST, 'ComputeButton');
if (!IsSet($w))
// ----------------------------------------------------
// If [COMPUTE] button was clicked and an active cookie
// exists, then restore the previous interface settings
// from it.
{
$w = Filter_Input(INPUT_COOKIE, $CookieName);
if (IsSet($w))
{
$InterfaceSettings = Filter_Input(INPUT_COOKIE, $CookieName);
list($Arg1) = Preg_Split("[\|]", $InterfaceSettings);
}
else
// Set the initial default interface startup values.
{
$Arg1 = 'One Two Three Four';
// Store text string in cookie.
$InterfaceSettings = $Arg1;
setcookie ($CookieName, $InterfaceSettings, $SetToExpireIn7Days);
}
} // End of if (!isset(_POST['ComputeButton']))
// =======================================
// Read values of all interface arguments.
// Empty value is set to zero by default.
$w = Filter_Input(INPUT_POST, 'ComputeButton');
if (isset($w))
{
$Arg1 = trim(Filter_Input(INPUT_POST, 'Arg1'));
// ------------------------------------
// Store interface arguments in cookie.
$InterfaceSettings = $Arg1;
SetCookie ($CookieName, $InterfaceSettings, $SetToExpireIn7Days);
}
// ========================================
// Check for error. FALSE = Error detected.
// Change this code to detect errors.
//
// Initially, any non-numeric argument causes
// an error.
$ErrFlag = FALSE;
// ===================================================
// Begin computations here if no error detected above.
// Convert string into array.
$Arg1 = PReg_Replace("/\s+/", ' ', trim($Arg1));
$Arg1Array = PReg_Split("[ ]", $Arg1);
$WordCount = count($Arg1Array);
if ($WordCount < 9)
{$PermsArray = Permutations_Array($Arg1Array);}
else
{$PermsArray = '';}
if ($WordCount < 9)
{
$N = $R = trim($WordCount); $N = bcAdd($N,0); $R = bcAdd($R,0);
$NP = 1; for ($i=0; $i < $R; $i++) {$NP = bcMul($NP, $N-$i);}
$n = 1; // Initialize permutations count.
$N = $R = trim($WordCount-1); $N = bcAdd($N,0); $R = bcAdd($R,0);
$BreakPoint = 1;
for ($i=0; $i < $R; $i++) {$BreakPoint = bcMul($BreakPoint, $N-$i);}
// Process up to 8 words or items.
for($i=0; $i < $NP; $i++)
{
// Format index value to 5 padded chars.
$nnnnn = SPrintf("% 5d", $n);
$w = $PermsArray[$i];
$u = '';
for ($j=0; $j < $WordCount; $j++)
{@$u .= $w[$j] . ' ';}
@$x .= "$nnnnn " . trim("'" . $u) . "'\n";
// Insert extra blank line when first word in permutation changes in
// order to separate the permutations into neat groupings starting
// with each word or item in succession.
if ($i % ($BreakPoint) == $BreakPoint-1) {@$x .= "\n";}
$n++;
}
// Adjust output text for proper English grammar.
$IsAre = ($NP < 2)? ' is':' are';
$s = ($NP < 2)? '':'s';
$S = ($NP < 2)? '':'S';
$EmptyString = ($Arg1 == '')? ' text string':' text string';
$NP = Number_Format($NP, 0);
$EmptyStrNote = ($Arg1 == '')? "An empty string still\ncounts as 1 permutation.":'';
// =======================================
// Print permutations list to text area 1.
$TextArea1Text =
"
Permutations are the total count of all the unique possible
sequences in which unique items can be arranged in a line
without duplicating any sequence, assuming that all of the
items or words in the string are unique and distinguishable
from each other.
Even if the listing is far too long to print, we can still
very easily compute the total number of possible permutations
exactly.
==============================================================
Given the plain text string:
'$Arg1'
There$IsAre exactly $NP possible word or item permutation$s
within the given$EmptyString. $EmptyStrNote
--------------------------------------------------------------
INDEXED TABLE OF $NP PERMUTATION$S OF $WordCount UNIQUE ITEM$S
Count Listing of ALL Permutations of the Unique Items
----- -------------------------------------------------------
$x
==============================================================";
}
else
{
$N = $R = trim($WordCount); $N = bcAdd($N,0); $R = bcAdd($R,0);
$NP = 1; for ($i=0; $i < $R; $i++) {$NP = bcMul($NP, $N-$i);}
$NP = number_format($NP,0);
$TextArea1Text =
"ALERT:
The table is too large to display. However, the total number of
possible permutations equates to exactly:
$NP
Due to resource and time constraints, the text string argument
is limited to eight words or text items separated by spaces.
When the number of words or text items exceeds 8, the program
will still compute the total number of possible permutations,
as shown above, but no table will be displayed.
Permutations for 9 items would require 362,880 lines to display
them all and 10 items would take 3,628,800 lines to display
them all. The number of permutations rapidly increases to
extremely large values impractical to tabulate in a web
browser or print to paper.
";
}
// Determine the number of text rows to use in the output TextAreas.
$TextArea1Rows = 2 + substr_count($TextArea1Text, "\n");
print <<< _HTML
<!DOCTYPE HTML>
<HTML lang='en'>
<head>
<title>Word Permutations Lister</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="description" content="This program lists the various permutations of words in a string.">
<meta name="keywords" content="string premutaations,text permutations,permutations list,permutations count">
<meta name="author" content="Jay Tanner - https://www.PHPScienceLabs.com">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta name="robots" content="index,follow">
<meta name="googlebot" content="index,follow">
<link rel="canonical" href="https://www.phpsciencelabs.com/word-permutations-lister/">
<style>
BODY
{color:silver; background-color:black; font-family:Verdana; font-size:100%}
TABLE
{font-size:12px; border: 1px solid black;}
TD
{color:black; background-color:white; line-height:200%; font-size:100%;
padding:6px; text-align:center;}
TEXTAREA
{
color:black; background:white; font-family:monospace; font-size:13pt;
font-weight:bold; border-radius: 8px; border:1px solid black; padding:4px;
white-space:pre;
}
INPUT[type="text"]::-ms-clear {width:0; height:0;}
INPUT[type="text"]
{
color:black; background:white; font-size:180%; font-family:monospace;
font-weight:bold; text-align:center; box-shadow:2px 2px 3px #666666;
border:2px solid black; border-radius:4px;
}
INPUT[type="text"]:focus
{
background:white; box-shadow:2px 2px 3px #666666; font-family:monospace;
font-size:180%; border:2px solid blue; text-align:center; font-weight:bold;
border-radius:4px;
}
INPUT[type="submit"]
{font-weight:bold;}
INPUT[type="submit"]:hover
{box-shadow:2px 2px 5px #555555; font-weight:bold;}
HR {background:black; height:2px; border:0px;}
A:link
{
font-size:100%; background:transparent; color:DodgerBlue; font-family:Verdana;
font-weight:bold; text-decoration:none; line-height:175%; padding:3px;
border:1px solid transparent;
}
A:visited {font-size:100%; background:transparent; color:silver;}
A:hover
{
font-size:100%; background:yellow; color:black; border:1px solid black;
box-shadow:1px 1px 3px #222222;
}
A:active {font-size:100%; background:yellow; color:black;}
::selection {background-color:yellow; color:black;}
::-moz-selection {background-color:yellow; color:black;}
</style>
</head>
<body>
<form name='form1' method='post' action="$_RUN_">
<table align='center' width='600' border='0' cellspacing='1' cellpadding='3'>
<tr><td colspan="$ColSpan" style='color:white; background-color:#000044; border:2px solid white; border-radius:8px 8px 0px 0px;'><b>$_INTERFACE_TITLE_</b>PHP Program by Jay Tanner</td></tr>
<tr><td style='background:LightYellow;'><b>Enter a Text String Containing Up To 8 UNIQUE Words or Items</b><br>
<input name='Arg1' type='text' value="$Arg1" size='66' maxlength='80'>
</td></tr>
<tr><td colspan="$ColSpan" style='background-color:black;'>
<input name='ComputeButton' type='submit' value=' C O M P U T E '>
</td></tr>
<!-- Yellow source code view link. --->
<tr>
<td colspan='1' style='background:transparent; color:black; font-size:10pt;
text-align:center;'>
<a href='View-Source-Code.php' target='_blank'
style='font-family:Verdana; color:black; background:yellow;
text-decoration:none; border:1px solid black; padding:4px;
border-radius:4px;'>
<span style='font-weight:normal;'>View/Copy PHP Source Code</span> </a>
</td>
</tr>
<tr>
<td colspan="$ColSpan" style='background-color:black;'>
<textarea name='TextArea1' style='color:$TxColor; background:$BgColor; padding:6px; border:2px solid white;' cols="64" rows="$TextArea1Rows" readonly>
$TextArea1Text
</textarea></td>
</tr>
<tr><td colspan="$ColSpan" style='color:gray; background:black;'>Program by $_AUTHOR_<br>$_REVISION_DATE_</td></tr>
$DLLink
</table>
</form>
<br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br>
</body>
_HTML;
/*
This function returns a table of all possible
permutations of up to 8 unique words or items.
*/
function Permutations_Array($input)
{
// Read input array values or words.
$input = Array_Values($input);
// Handle case of single word argument.
if (count($input) == 1) {return array($input);}
// Otherwise, cycle through and collect
// list of all possible permutations.
$result = [];
$N = count($input); // Count words or items.
for ($i=0; $i < $N; $i++)
{
$copy = $input;
$value = Array_Splice($copy, $i, 1);
ForEach (Permutations_Array($copy) as $permutation)
{
Array_Unshift($permutation, $value[0]);
$result[] = $permutation;
}
}
return $result;
}
?>