Fork me on GitHub

Kaprekar's Constant - 6174

6174 looks pretty straightforward but try this.
Sort it by highest to lowest digit : 7641
Reverse the resulting number : 1467
Subtracting 1467 from 7641 leaves 6174

We get to Kaprekar's constant. 6174. That whole iteration is called Kaprekar's routine and any 4 digit number that has at least 2 different digits will reach 6174 in at most 7 iterations. Which this script replicates. 

Kaprekars constant

function kapsort($random, $highToLow = false){
 
  $count =strlen($random);
  $sorted = '';
  $arrParts = array();

  for ($i=0; $i<$count; $i++){
    $parts[$i] = $random[$i];
  }

  if($highToLow){
    arsort($parts);
  } else {
    asort($parts);
  }

  foreach($parts as $val){
    $sorted .= $val;
  }

  return $sorted;

}

$n = (string)rand(1000,9999);

echo "<table>";
echo "<caption>Candidate : {$n}</caption>";
echo "<tr><th></th><th>Descending</th><th>Ascending</th><th></th>";
$j=0;
while ($n != 6174) {
  $sortedHigh2Low = kapsort((string)$n, true);
  $sortedLow2High = kapsort((string)$n, false);
  echo "<tr>";
  echo "<td width=\"100\">$n</td><td width=\"100\">".$sortedHigh2Low."</td>";
  echo "<td width=\"100\">".$sortedLow2High."</td>";
  $n = $sortedHigh2Low - $sortedLow2High;
  echo "<td>{$sortedHigh2Low}-{$sortedLow2High}=$n</td></tr>";
  $j++;
  if($j>=8) {
    $j=0;
    exit("kaprekar not found, probably a number with 3 digits the same");
  }
}
echo "</table>";

echo "Kaprekar in {$j} iterations \n";

Example random number. Reload for a new number.

Candidate : 6786
descasc
6786876666788766-6678=2088
2088882002888820-0288=8532
8532853223588532-2358=6174
Kaprekar in 3 iterations