Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Does '6k views' mean and how can I format the number in PHP

Tags:

php

What does "6k views" mean and how can I format this number in PHP?

like image 905
Mostafa Elkady Avatar asked Apr 24 '10 09:04

Mostafa Elkady


2 Answers

k is the abbreviation for the Kilo prefix and means thousand. So 6k means six thousand.

You can format a number in such a way with the following function using division:

function format($number) {
    $prefixes = 'kMGTPEZY';
    if ($number >= 1000) {
        for ($i=-1; $number>=1000; ++$i) {
            $number /= 1000;
        }
        return floor($number).$prefixes[$i];
    }
    return $number;
}

Or using logarithm base 10 and exponentiation:

function format($number) {
    $prefixes = 'kMGTPEZY';
    if ($number >= 1000) {
        $log1000 = floor(log10($number)/3);
        return floor($number/pow(1000, $log1000)).$prefixes[$log1000-1];
    }
    return $number;
}
like image 126
Gumbo Avatar answered Oct 01 '22 21:10

Gumbo


'6k views' on StackOverflow refers to the number of views a question has received. It means 6000 views.

If you're looking to format a similar style number in php then try something like

$number = "";
if( $value > 1000 )
{
    $number .= floor($value / 1000) . "k";
} else {
    $number .= $value;
}
echo $number . " views".

Obviously you can add cases for m, g and t views if desired.

like image 39
Geoff Avatar answered Oct 01 '22 19:10

Geoff