How to make a K-Style Facebook/Twitter Counter in PHP

The idea here is that want numbers to only be represented by a base of thousands. This means 1,000 becomes 1K, 1,000,000 becomes 1M and so on. This is similar to how Facebook share buttons display share or like counts as well as Twitter buttons. To implement this we will need to rely on the log() function.

<?php
function shortNumbers(Int $number): String {
    if ($number < 1000) {
        return (string) $number;
    }
    
    if ($number > 999999999999999) {
        throw new Exception("Number is too large!");
    }

    $orders = ['', 'K', 'M', 'B', 'T'];
    
    $order     = log($number, 1000);
    $magnitude = (int) $order;
    $float     = (1000 ** $order) / (1000 ** $magnitude);
    $n         = $float < 100 ? 1 : 0;
    $size      = sprintf("%.{$n}f", $float);
    
    if (strpos($size, '.') !== false) {
        $size = rtrim($size, '0');
        $size = rtrim($size, '.');
    }

    return sprintf("%s%s", $size, $orders[$magnitude]);
}

echo shortNumbers(123724); // 124K