How to format numbers in php 1,000 to 1k - php

Im trying to format the output of numbers in php. I have an amount of posts that show up, and next to each user is the total of posts. But it shows that actual amount, i want it to show it in a shorter format, actually, just like they do here at SO with reputation
any ideas?

<?
$numbers = array(100,1000,15141,3421);
function format_number($number) {
if($number >= 1000) {
return $number/1000 . "k"; // NB: you will want to round this
}
else {
return $number;
}
}
foreach($numbers as $number) {
echo $number . " : " . format_number($number);
echo "\n";
}

function count_format($n, $point='.', $sep=',') {
if ($n < 0) {
return 0;
}
if ($n < 10000) {
return number_format($n, 0, $point, $sep);
}
$d = $n < 1000000 ? 1000 : 1000000;
$f = round($n / $d, 1);
return number_format($f, $f - intval($f) ? 1 : 0, $point, $sep) . ($d == 1000 ? 'k' : 'M');
}

Use This
Shorten long numbers to K/M/B?
function number_format_short( $n, $precision = 1 ) {
if ($n < 900) {
// 0 - 900
$n_format = number_format($n, $precision);
$suffix = '';
} else if ($n < 900000) {
// 0.9k-850k
$n_format = number_format($n / 1000, $precision);
$suffix = 'K';
} else if ($n < 900000000) {
// 0.9m-850m
$n_format = number_format($n / 1000000, $precision);
$suffix = 'M';
} else if ($n < 900000000000) {
// 0.9b-850b
$n_format = number_format($n / 1000000000, $precision);
$suffix = 'B';
} else {
// 0.9t+
$n_format = number_format($n / 1000000000000, $precision);
$suffix = 'T';
}

Related

there was an error in php when the function was placed inside while

I tried to make results like Facebook, but this doesn't work with my code, can you tell me where I did wrong?
sorry because I just learned php
This is my code :
<?php try {
$news_popular = "SELECT * FROM dUfA1_article ORDER BY id DESC";
$news_popular1 = $pdo->prepare($news_popular);
$news_popular1 ->execute(); }
catch (PDOException $exception) {
echo "ada kesalahan pada query : ".$exception->getMessage();
}
while ($data = $news_popular1->fetch(PDO::FETCH_ASSOC)) {
$ttl_likes = $data['likes'];
function number_format_short( $ttl, $precision = 1 ) {
if ($ttl < 900) {
$n_format = number_format($ttl, $precision);
$suffix = '';
} else if ($ttl < 900000) {
$n_format = number_format($ttl / 1000, $precision);
$suffix = 'K';
} else if ($ttl < 900000000) {
$n_format = number_format($ttl / 1000000, $precision);
$suffix = 'M';
} else if ($ttl < 900000000000) {
$n_format = number_format($ttl / 1000000000, $precision);
$suffix = 'B';
} else {
$n_format = number_format($ttl / 1000000000000, $precision);
$suffix = 'T';
}
if ( $precision > 0 ) {
$dotzero = '.' . str_repeat( '0', $precision );
$n_format = str_replace( $dotzero, '', $n_format );
}
return $n_format . $suffix;
}
$likes = number_format_short($ttl_likes);
echo " hasil = $likes <br>";
}?>
You can declare function with the same only once. Your number_format_short() declaration written inside the while loop so that if you while loop execute 5 times number_format_short() declare 5 times with the same.
Use below code
try {
$news_popular = "SELECT * FROM dUfA1_article ORDER BY id DESC";
$news_popular1 = $pdo->prepare($news_popular);
$news_popular1->execute();
} catch (PDOException $exception) {
echo "ada kesalahan pada query : " . $exception->getMessage();
}
while ($data = $news_popular1->fetch(PDO::FETCH_ASSOC)) {
$ttl_likes = $data['likes'];
$likes = number_format_short($ttl_likes);
echo " hasil = $likes <br>";
}
function number_format_short($ttl, $precision = 1) {
if ($ttl < 900) {
$n_format = number_format($ttl, $precision);
$suffix = '';
} else if ($ttl < 900000) {
$n_format = number_format($ttl / 1000, $precision);
$suffix = 'K';
} else if ($ttl < 900000000) {
$n_format = number_format($ttl / 1000000, $precision);
$suffix = 'M';
} else if ($ttl < 900000000000) {
$n_format = number_format($ttl / 1000000000, $precision);
$suffix = 'B';
} else {
$n_format = number_format($ttl / 1000000000000, $precision);
$suffix = 'T';
}
if ($precision > 0) {
$dotzero = '.' . str_repeat('0', $precision);
$n_format = str_replace($dotzero, '', $n_format);
}
return $n_format . $suffix;
}
?>
<?php
function number_format_short( $ttl, $precision = 1 ) {
if ($ttl < 900) {
$n_format = number_format($ttl, $precision);
$suffix = '';
} else if ($ttl < 900000) {
$n_format = number_format($ttl / 1000, $precision);
$suffix = 'K';
} else if ($ttl < 900000000) {
$n_format = number_format($ttl / 1000000, $precision);
$suffix = 'M';
} else if ($ttl < 900000000000) {
$n_format = number_format($ttl / 1000000000, $precision);
$suffix = 'B';
} else {
$n_format = number_format($ttl / 1000000000000, $precision);
$suffix = 'T';
}
if ( $precision > 0 ) {
$dotzero = '.' . str_repeat( '0', $precision );
$n_format = str_replace( $dotzero, '', $n_format );
}
return $n_format . $suffix;
}
try {
$news_popular = "SELECT * FROM dUfA1_article ORDER BY id DESC";
$news_popular1 = $pdo->prepare($news_popular);
$news_popular1->execute();
} catch (PDOException $exception) {
echo "ada kesalahan pada query : ".$exception->getMessage();
}
while ($data = $news_popular1->fetch(PDO::FETCH_ASSOC)) {
$ttl_likes = $data['likes'];
$likes = number_format_short($ttl_likes);
echo " hasil = $likes <br>";
}
?>

How to make the function Global in Codeigniter application

I am trying to make the function global in CodeIgniter application. I have created a PHP file Constant.php in application/libraries.
Constant.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Constant
{
public function custom_number_format($n, $precision = 1) {
if ($n < 900) {
// 0 - 900
$n_format = number_format($n, $precision);
$suffix = '';
} else if ($n < 900000) {
// 0.9k-850k
$n_format = number_format($n / 1000, $precision);
$suffix = 'K';
} else if ($n < 900000000) {
// 0.9m-850m
$n_format = number_format($n / 1000000, $precision);
$suffix = 'M';
} else if ($n < 900000000000) {
// 0.9b-850b
$n_format = number_format($n / 1000000000, $precision);
$suffix = 'B';
} else {
// 0.9t+
$n_format = number_format($n / 1000000000000, $precision);
$suffix = 'T';
}
// Remove unecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1"
// Intentionally does not affect partials, eg "1.50" -> "1.50"
if ( $precision > 0 ) {
$dotzero = '.' . str_repeat( '0', $precision );
$n_format = str_replace( $dotzero, '', $n_format );
}
return $n_format . $suffix;
}
}
I have declared this library in the config/autoload.php something like
$autoload['libraries'] = array('constant');
and now I trying to access this library something like
$totalview=$this->Constant->custom_number_format($views);
But I am getting the following error
I'm not totally sure, but I think you should call as declared.
If you declared it as:
$autoload['libraries'] = array('constant');
You should call it as:
$totalview=$this->constant->custom_number_format($views);
(with lowercase).

Short Number format in PHP Indian Based

Googled for Short Number Format in PHP, got thousands of working results from StackOverflow, Github, etc.. but I didn't get any results for Indian Format.
Eg:
In other countries: 1000 is as 1k, 100000 is as 100k, 10000000 is as 10m
But in India: 1000 is as 1k OR 1T, 100000 is as 1L, 10000000 is as 1c
Can anyone help me to do that?
With the help of this answer
I came up with a solution for you:
<?php
function indian_short_number($n) {
if($n <= 99999){
$precision = 3;
if ($n < 1000) {
// Anything less than a thousand
$n_format = number_format($n);
} else {
// At least a thousand
$n_format = number_format($n / 1000, $precision) . ' K';
}
/* Use this code if you want to round off your results
$n_format = ceil($n_format / 10) * 10;
if($n >= 1000){
$n_format = $n_format . ' K';
}
*/
return $n_format;
}
else{
$precision = 2;
if ($n > 99999 && $n < 9999999) {
// Anything more than a Lac and less than crore
$n_format = number_format($n / 100000, $precision) . ' L';
} elseif ($n > 999999) {
// At least a crore
$n_format = number_format($n / 10000000, $precision) . ' C';
}
/* Use this code if you want to round off your results
$n_format = ceil($n_format / 10) * 10;
if($n >= 10000 && $n < 10000000){
$n_format = $n_format . ' L';
}
elseif($n >= 1000000){
$n_format = $n_format . ' C';
}
*/
return $n_format;
}
}
echo indian_short_number(10000);
?>
The code for rounding off is not proper. (For 18100 it rounds to 20 K instead of 19 K)
I will be thankful if any of the visitors edit the answer with the fixing it.
Hope it helps you.

human readable file size

function humanFileSize($size)
{
if ($size >= 1073741824) {
$fileSize = round($size / 1024 / 1024 / 1024,1) . 'GB';
} elseif ($size >= 1048576) {
$fileSize = round($size / 1024 / 1024,1) . 'MB';
} elseif($size >= 1024) {
$fileSize = round($size / 1024,1) . 'KB';
} else {
$fileSize = $size . ' bytes';
}
return $fileSize;
}
... works great except: I can't manually choose in what format I need to display, say i want to show in MB only whatever the file size is. Currently if its in the GB range, it would only show in GB.
Also, how do I limit the decimal to 2?
Try something like this:
function humanFileSize($size,$unit="") {
if( (!$unit && $size >= 1<<30) || $unit == "GB")
return number_format($size/(1<<30),2)."GB";
if( (!$unit && $size >= 1<<20) || $unit == "MB")
return number_format($size/(1<<20),2)."MB";
if( (!$unit && $size >= 1<<10) || $unit == "KB")
return number_format($size/(1<<10),2)."KB";
return number_format($size)." bytes";
}
There is great example by Jeffrey Sambells:
function human_filesize($bytes, $dec = 2): string {
$size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$factor = floor((strlen($bytes) - 1) / 3);
if ($factor == 0) $dec = 0;
return sprintf("%.{$dec}f %s", $bytes / (1024 ** $factor), $size[$factor]);
}
echo human_filesize(filesize('example.zip'));
I'm using this method:
function byteConvert($bytes)
{
if ($bytes == 0)
return "0.00 B";
$s = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
$e = floor(log($bytes, 1024));
return round($bytes/pow(1024, $e), 2).$s[$e];
}
works great in o(1).
A pretty short 3 lines method that I use (1024 = 1KB) and supports from KB to YB is the following one:
<?php
/**
* Converts a long string of bytes into a readable format e.g KB, MB, GB, TB, YB
*
* #param {Int} num The number of bytes.
*/
function readableBytes($bytes) {
$i = floor(log($bytes) / log(1024));
$sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
return sprintf('%.02F', $bytes / pow(1024, $i)) * 1 . ' ' . $sizes[$i];
}
// "1000 B"
echo readableBytes(1000);
// "9.42 MB"
echo readableBytes(9874321);
// "9.31 GB"
// The number of bytes as a string is accepted as well
echo readableBytes("10000000000");
// "648.37 TB"
echo readableBytes(712893712304234);
// "5.52 PB"
echo readableBytes(6212893712323224);
More info about these methods on this article.
To expand on Vaidas' answer, here's how you should do it to account for the new IEC standards:
function human_readable_bytes($bytes, $decimals = 2, $system = 'binary')
{
$mod = ($system === 'binary') ? 1024 : 1000;
$units = array(
'binary' => array(
'B',
'KiB',
'MiB',
'GiB',
'TiB',
'PiB',
'EiB',
'ZiB',
'YiB',
),
'metric' => array(
'B',
'kB',
'MB',
'GB',
'TB',
'PB',
'EB',
'ZB',
'YB',
),
);
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f%s", $bytes / pow($mod, $factor), $units[$system][$factor]);
}
Technically, according to the specifications for storage devices and such you should use the metric system as default (that's why Google converter shows kB -> MB as mod 1000 instead of 1024).
Here's my custom function for displaying human readable file size:
function getHumanReadableSize($bytes) {
if ($bytes > 0) {
$base = floor(log($bytes) / log(1024));
$units = array("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"); //units of measurement
return number_format(($bytes / pow(1024, floor($base))), 3) . " $units[$base]";
} else return "0 bytes";
}
function bytesToHuman($bytes)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
for ($i = 0; $bytes > 1024; $i++) $bytes /= 1024;
return round($bytes, 2) . ' ' . $units[$i];
}
Credit: https://laracasts.com/discuss/channels/laravel/human-readable-file-size-and-time?page=1#reply=115796
You can modify your function to fullfil both your need to force a unit if given and adjust the precision.
function humanFileSize($size, $precision = 1, $show = "")
{
$b = $size;
$kb = round($size / 1024, $precision);
$mb = round($kb / 1024, $precision);
$gb = round($mb / 1024, $precision);
if($kb == 0 || $show == "B") {
return $b . " bytes";
} else if($mb == 0 || $show == "KB") {
return $kb . "KB";
} else if($gb == 0 || $show == "MB") {
return $mb . "MB";
} else {
return $gb . "GB";
}
}
//Test with different values
echo humanFileSize(1038) . "<br />";
echo humanFileSize(103053, 0) . "<br />";
echo humanFileSize(103053) . "<br />";
echo humanFileSize(1030544553) . "<br />";
echo humanFileSize(1030534053405, 2, "GB") . "<br />"; ;
function getHumanReadableSize($size, $unit = null, $decemals = 2) {
$byteUnits = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
if (!is_null($unit) && !in_array($unit, $byteUnits)) {
$unit = null;
}
$extent = 1;
foreach ($byteUnits as $rank) {
if ((is_null($unit) && ($size < $extent <<= 10)) || ($rank == $unit)) {
break;
}
}
return number_format($size / ($extent >> 10), $decemals) . $rank;
}
If php version below 5.4 use
$byteUnits = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
I wanted a function that returned filesizes like Windows does, and surprisingly I could find none at all. Even worse, some here and elsewhere are broken in that they assume 1KB = 1000B.
So I coded one! Plus two helper functions. Here they are:
// Returns a size in a human-readable form from a byte count.
function humanSize($bytes)
{
if ($bytes < 1024) return "$bytes Bytes";
$units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
foreach ($units as $i => $unit)
{
// The reason for this threshold is to avoid e.g., "1000 KB",
// instead jumping from e.g., "999 KB" to "0.97 MB".
$multiplier = pow(1024, $i + 1);
$threshold = $multiplier * 1000;
if ($bytes < $threshold)
{
$size = formatToMinimumDigits($bytes / $multiplier, false);
return "$size $unit";
}
}
}
// Efficiently calculates how many digits the integer portion of a number has.
function digits($number)
{
// Yes, I could convert to string and count the characters,
// but this is faster and cooler.
$log = log10($number);
if ($log < 0) return 1;
return floor($log) + 1;
}
// Formats a number to a minimum amount of digits.
// In other words, makes sure that a number has at least $digits on it, even if
// that means introducing redundant decimal zeroes at the end, or rounding the
// ones present exceeding the $digits count when combined with the integers.
// For example:
// formatToMinimumDigits(10) // 10.0
// formatToMinimumDigits(1.1) // 1.10
// formatToMinimumDigits(12.34) // 12.3
// formatToMinimumDigits(1.234) // 1.23
// formatToMinimumDigits(1.203) // 1.20
// formatToMinimumDigits(123.4) // 123
// formatToMinimumDigits(100) // 100
// formatToMinimumDigits(1000) // 1000
// formatToMinimumDigits(1) // 1.00
// formatToMinimumDigits(1.002) // 1.00
// formatToMinimumDigits(1.005) // 1.01
// formatToMinimumDigits(1.005, false) // 1.00
// This is primarily useful for generating human-friendly numbers.
function formatToMinimumDigits($value, $round = true, $digits = 3)
{
$integers = floor($value);
$decimalsNeeded = $digits - digits($integers);
if ($decimalsNeeded < 1)
{
return $integers;
}
else
{
if ($round)
{
// This relies on implicit type casting of float to string.
$parts = explode('.', round($value, $decimalsNeeded));
// We re-declare the integers because they may change
// after we round the number.
$integers = $parts[0];
}
else
{
// Again, implicit type cast to string.
$parts = explode('.', $value);
}
// And because of the implicit type cast, we must guard against
// 1.00 becoming 1, thus not exploding the second half of it.
$decimals = isset($parts[1]) ? $parts[1] : '0';
$joined = "$integers.$decimals".str_repeat('0', $digits);
return substr($joined, 0, $digits + 1);
}
}
Usage is as simple as humanSize(123456789).
This is how I use, it's clean and simple.
Also can be used like this:
public function getHumanReadableFilesize(int $bytes, int $dec = 2): string
{
$size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$dec}f %s", ($bytes / (1024 ** $factor)), $size[$factor]);
}
Thanks #Márton Tamás for suggestion to add like comment.
Here is a working function managing till Yottabyte:
function DisplayFileSize($size, $unit = false, $precision = 2){
$b = $size;
$kb = round($size / 1024, $precision);
$mb = round($kb / 1024, $precision);
$gb = round($mb / 1024, $precision);
$tb = round($gb / 1024, $precision);
$pb = round($tb / 1024, $precision);
$eb = round($pb / 1024, $precision);
$zb = round($eb / 1024, $precision);
$yb = round($zb / 1024, $precision);
if((!$unit && floor($kb) == 0) || $unit == "b") {
return array("value" => FormatNumber($b), "unit" => "bytes");
} else if((!$unit && floor($mb) == 0) || $unit == "kb") {
return array("value" => FormatNumber($kb, 2), "unit" => "Kb");
} else if((!$unit && floor($gb) == 0) || $unit == "mb") {
return array("value" => FormatNumber($mb, 2), "unit" => "Mb");
} else if((!$unit && floor($tb) == 0) || $unit == "gb") {
return array("value" => FormatNumber($gb, 2), "unit" => "Gb");
} else if((!$unit && floor($pb) == 0) || $unit == "tb") {
return array("value" => FormatNumber($tb, 2), "unit" => "Tb");
} else if((!$unit && floor($eb) == 0) || $unit == "pb") {
return array("value" => FormatNumber($pb, 2), "unit" => "Pb");
} else if((!$unit && floor($zb) == 0) || $unit == "eb") {
return array("value" => FormatNumber($eb, 2), "unit" => "Eb");
} else if((!$unit && floor($yb) == 0) || $unit == "zb") {
return array("value" => FormatNumber($zb, 2), "unit" => "Zb");
} else {
return array("value" => FormatNumber($yb, 2), "unit" => "Yb");
}
}

Using PHP to grab a simplified colour palette from an image?

So far I have found examples on how to grab all the RGB values of each pixel in an image but I want something that will break down an image and give me a simplified color palette.
Is there a way to use imagetruecolortopalette to somehow spit out the reduced palette colours, or to break an image into 25 x 25 blocks and then grab the average value of that block?
Maybe there is an alternative I'm missing? I basically just want to be able to find the most common colors within an image.
Thanks in advance.
Hmm, well I have had created something like this for a client. The screenshot is below
The complete code is as follows
$microTime = microtime(true);
function textColor($R1, $G1, $B1) {
$a = (($R1 * 299) + ($G1 * 587 ) + ($B1 * 114 )) / 1000;
if ($a < 128)
return 'white';
else
return 'black';
}
function rgb2html($r, $g = -1, $b = -1) {
$hex = "#";
$hex.= str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
return $hex;
if (is_array($r) && sizeof($r) == 3)
list($r, $g, $b) = $r;
$r = intval($r);
$g = intval($g);
$b = intval($b);
$r = dechex($r < 0 ? 0 : ($r > 255 ? 255 : $r));
$g = dechex($g < 0 ? 0 : ($g > 255 ? 255 : $g));
$b = dechex($b < 0 ? 0 : ($b > 255 ? 255 : $b));
$color = (strlen($r) < 2 ? '0' : '') . $r;
$color .= (strlen($g) < 2 ? '0' : '') . $g;
$color .= (strlen($b) < 2 ? '0' : '') . $b;
return '#' . $color;
}
function colorPalette($imageFile, $colorJump, $granularity = 5) {
$granularity = max(1, abs((int) $granularity));
$colors = array();
$ratio = array();
$wastageCount = array();
$occurrenceSCount = array();
$occurrenceMCount = array();
$size = #getimagesize($imageFile);
if ($size === false) {
return false;
}
$img = #imagecreatefromstring(file_get_contents($imageFile));
if (!$img) {
user_error("Unable to open image file");
return false;
}
for ($y = 0; $y < $size[1]; $y += $granularity) {
$lastColor = NULL;
$lastX = -1;
for ($x = 0; $x < $size[0]; $x += $granularity) {
$thisColor = imagecolorat($img, $x, $y);
$rgb = imagecolorsforindex($img, $thisColor);
$red = round(round(($rgb['red'] / $colorJump)) * $colorJump);
$green = round(round(($rgb['green'] / $colorJump)) * $colorJump);
$blue = round(round(($rgb['blue'] / $colorJump)) * $colorJump);
$thisRGB = $red . ',' . $green . ',' . $blue;
if ($lastColor != $thisRGB) {
if (array_key_exists($thisRGB, $wastageCount)) {
$wastageCount[$thisRGB]++;
} else {
$wastageCount[$thisRGB] = 1;
}
if ($lastX + 1 == $x) {
if (array_key_exists($lastColor, $occurrenceSCount)) {
$occurrenceSCount[$lastColor]++;
} else {
$occurrenceSCount[$lastColor] = 1;
}
}
if ($lastX + 1 != $x) {
if (array_key_exists($lastColor, $occurrenceMCount)) {
$occurrenceMCount[$lastColor]++;
} else {
$occurrenceMCount[$lastColor] = 1;
}
}
$lastColor = $thisRGB;
$lastX = $x;
}
if (array_key_exists($thisRGB, $colors)) {
$colors[$thisRGB]++;
} else {
$colors[$thisRGB] = 1;
}
}
}
$totalPixels = array_sum($colors);
foreach ($colors as $k => $v) {
$ratio[$k] = round(($v / $totalPixels ) * 100, 2);
}
return array($ratio, $wastageCount, $colors, $occurrenceSCount, $occurrenceMCount);
}
usage
$colorJump = 1;
$pixelJump = 1;
$paletteR = colorPalette($dbImgFile_dir, $colorJump, $pixelJump);
$palette = $paletteR[0];
$wastage = $paletteR[1];
$colorsFound = $paletteR[2];
$occSArray = $paletteR[3];
$occMArray = $paletteR[4];
$totalPixels = array_sum($colorsFound);
$totalTime = abs(microtime(true) - $microTime);
the looping around is more complex, as I have to get the pallet from the DB and to match the colors with them, and also the template parser is used which is full custom code, and will not help you.
Just ignore the Required Weight column from this, the single occurrences and multiple occurrences are calculated, if there is a single pixel, for example RED, RED, BLUE, RED, RED it will be 1 single occurrence and 2 multiple occurrence

Categories