PHP Number Format 1000 to 1K

How to format numbers in PHP. Below PHP function code for Thousands number format to 1K. Convert large number into short K M B T

1000 = 1K one thousand
1,000,000 = 1M one million
1,000,000,000 = 1B one billion

PHP Function Thousand Format

PHP
<?php
function thousand_format($number) {
    $number = (int) preg_replace('/[^0-9]/', '', $number);
    if ($number >= 1000) {
        $rn = round($number);
        $format_number = number_format($rn);
        $ar_nbr = explode(',', $format_number);
        $x_parts = array('K', 'M', 'B', 'T', 'Q');
        $x_count_parts = count($ar_nbr) - 1;
        $dn = $ar_nbr[0] . ((int) $ar_nbr[1][0] !== 0 ? '.' . $ar_nbr[1][0] : '');
        $dn .= $x_parts[$x_count_parts - 1];

        return $dn;
    }
    return $number;
}
?>

Usage PHP Thousand Format

PHP
<?php
    echo thousand_format(999);  // 999
    
    echo thousand_format(1000);  // 1K

    echo thousand_format(1000000);  // 1M



    echo thousand_format('999');  // 999

    echo thousand_format('1000');  // 1K

    echo thousand_format('1,000,000');  // 1M

    $viewers = '100000';
    echo '<div title="'.$viewers.'">'.thousand_format($viewers).'</div>';
?>