Convert MB nunber to GB or TB - php

In my code I am outputting a number from a database, the number is in MB.
So for example I am getting the HDD size and free space.
Looks like this:
C: CAP 1141919
C: FREE 487205
What I am trying to do is convert those number to either TB or GB
The output would look like:
C: CAP 1.141919TB
C: FREE 487.205GB
Further more I want to cut the input down to two decimal places.
C: CAP 1.14TB
C: FREE 487.20GB
I have tried a couple different functions however most of them want the number in bytes, which I did find a way to convert the number from MB to B then to GB but I ran into a problem with the TB, also im sure there is a way to do this in one step.
Any help would be appreciated.

function convert($size)
{
$filesizename = array(" MB", " GB", " TB");
$size = round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i];
return $size;
}
$test = convert(4000);
echo $test; //produces 3.91 GB

another variant:
function convertMB($mb) {
$mb = floatval($mb) / 1024.0;
return ($mb < 1024) ? (number_format($mb, 2).'GB') : (number_format($mb / 1024.0, 2).'TB');
}

Set decimal points by number_format function:
$number = number_format($number, 2); // 2 is decimal points

Related

Fastest way to compute & feed an arbitrary color centroid in an image to PHP

I'm looking for the fastest way to compute a directional vector based on an arbitrary color in an image (a Rpi camera, but a JPEG file for testing is OK for now), a.k.a. tracking a colored ball project. Please note that the resulting vector (or centroid coordinates, whatever) needs to be passed to PHP for the program execution, so the solution I'm looking for needs to end with PHP, but can be anything before, given it can be implemented on both Windows and Linux.
Consider an input JPEG image:
Here are 2 example directional vectors I'm after, obtained based on a 1) teal color input and 2) purple color input. Obviously, only 1 vector will ever be asked at a time, I put 2 to demonstrate multiple examples into 1 image, but it's always gonna be only 1 vector at a time. Note that the resulting vectors ("v") are standardized to -1.0 (bottom/left) to +1.0 (bottom/right) so that zero is the middle of the picture.
Here are the various solutions I've implemented/tested so far and how much time the whole process takes, based on a 960x640 JPEG picture, but the implemented solution will be tied to a Rpi camera input, I do not have the camera yet so I use a JPEG image until the camera arrives from China.
1) 2700ms : Use GD2 that is bundled with PHP, for loop over each pixels, push pixels matching ~10% RGB values in XY arrays, average the XY arrays, compute/normalize directional vector from XY arrays.
$arr_matching_pixels = array('arr_x' => array(), 'arr_y' => array());
for($y = 0; $y < $h - 1; $y++){
for($x = 0; $x < $w - 1; $x++){
$arr_pixel = imagecolorsforindex($img, imagecolorat($img, $x, $y));
if(abs($arr_pixel['red'] - $arr_seek_color['red']) < 30){
if(abs($arr_pixel['green'] - $arr_seek_color['green']) < 30){
if(abs($arr_pixel['blue'] - $arr_seek_color['blue']) < 30){
array_push($arr_matching_pixels['arr_x'], $x);
array_push($arr_matching_pixels['arr_y'], $y);
}
}
}
}
}
// Compute centroid of color... etc...
2) 700ms : Same as #1 except begin by resizing the canvas by 50% (acceptable loss) using imagecreatefromjpeg('_test_cam_img.jpg');
3) 560ms : Same as #2 except use ImageMagick with a pixel iterator loop to read the pixels
$imagick = new Imagick(realpath($o_img));
$arr_matching_pixels = array('arr_x' => array(), 'arr_y' => array());
$arr_pixel = array();
$iterator = $imagick->getPixelIterator();
foreach($iterator as $y => $pixels){
foreach($pixels as $x => $pixel){
$arr_pixel = $pixel->getColor();
if(abs($arr_pixel['r'] - $arr_seek_color['red']) < 30){
if(abs($arr_pixel['g'] - $arr_seek_color['green']) < 30){
if(abs($arr_pixel['b'] - $arr_seek_color['blue']) < 30){
array_push($arr_matching_pixels['arr_x'], $x);
array_push($arr_matching_pixels['arr_y'], $y);
}
}
}
}
}
// Compute centroid of color... etc...
4) 340ms : Call the system's ImageMagick binary via the exec() function, pass it the image location, the chroma/color key, a resize by 50% param, a 10% fuzz param, and the sparse-color: modifier to extract a textual (CSV-like) list representation of desired pixels, then use PHP to loop over each line, explode commas and push all pixels in XY arrays, average the XY arrays, compute/normalize directional vector from XY arrays. I noted that calling exec() proves to be quite slower than executing the same command directly from the Windows command line.
$imagick = new Imagick(realpath($o_img));
$out = exec('"E:\Users\Ben\Roaming Apps\imagemagick-6.9.3\convert" E:\wamp64\www\test_cam_img.jpg -resize 50% -fuzz 10% +transparent rgb(' . $arr_seek_color['red'] . ',' . $arr_seek_color['green'] . ',' . $arr_seek_color['blue'] . ') sparse-color:');
$arr_lines = explode(' ', $out);
$arr_matching_pixels = array('arr_x' => array(), 'arr_y' => array());
foreach($arr_lines as $str_line){
$arr_xy_coords = explode(',', $str_line);
array_push($arr_matching_pixels['arr_x'], $arr_xy_coords[0]);
array_push($arr_matching_pixels['arr_y'], $arr_xy_coords[1]);
}
// Compute centroid of color... etc...
5) 32ms : PHP creates an "in" text file containing the image path and the chroma/color key and begins looping until it reads an "out" text file. A python+OpenCV script already/always runs a (stoppable) infinite loop constantly looking for an "in" text file and when it exists, it read it, explodes the values, makes a 1-bit mask using the HSV values ~10% (cv2.inRange) from the "in" file, then makes an array using cv2.findNonZero(mask) and computes the array mean value and writes it to an "out" text file that PHP immediately reads, containing the directional vector value. This is by far, the fastest way I have found, but it is awkward, because it implies that the python script will have to be programmed in a CRONJOB and monitored/relaunched in a single instance if it crashes.
file_put_contents('_avg_color_coords_in.txt', $o_img . "\n" . $arr_seek_color['h'] . ',' . $arr_seek_color['s'] . ',' . $arr_seek_color['l']);
$starttime = time();
while((time() - $starttime) < 5){ // Max 5 seconds (exaggerated)
if(file_exists('_avg_color_coords_out.txt')){
$dir_vector = (float) file_get_contents('_avg_color_coords_out.txt');
if(!#unlink('_avg_color_coords_out.txt')){
sleep(1);
unlink('_avg_color_coords_out.txt');
}
break;
}
usleep(2000);
}
// $dir_vector ("v", the centroid of the color) is already computed by Python
// ---------- PYTHON SCRIPT ----------
import math
import cv2
import numpy as np
import os
import time
#cap = cv2.VideoCapture(0)
#while (1):
# _, frame = cap.read()
if(os.path.exists('_avg_color_coords_stop.txt')):
exit()
while not os.path.exists('_avg_color_coords_in.txt'):
time.sleep(0.002)
f = open('_avg_color_coords_in.txt', 'r')
imgsrc = f.readline().rstrip('\n')
rgbcol = [int(x) for x in f.readline().rstrip('\n').split(',')]
frame = cv2.imread(imgsrc)
h, w = frame.shape[:2]
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
hfacl = rgbcol[0] / 360 * 180 * 0.95
hfach = rgbcol[0] / 360 * 180 * 1.05
sfacl = rgbcol[1] / 100 * 255 * 0.9
sfach = rgbcol[1] / 100 * 255 * 1.1
vfacl = rgbcol[2] / 100 * 255 * 0.9
vfach = rgbcol[2] / 100 * 255 * 1.1
lower_color = np.array([hfacl, sfacl, vfacl]) # 0..180, 0..255, 0..255 not percentage!
upper_color = np.array([hfach, sfach, vfach]) # 0..180, 0..255, 0..255 not percentage!
mask = cv2.inRange(hsv, lower_color, upper_color)
#cv2.imshow('mask', mask)
points = cv2.findNonZero(mask)
if(points.any()):
avg = np.mean(points, axis=0)
else:
avg = [0,0]
#print(avg)
v = -math.atan(((w * 0.5) - avg[0][0]) / (h - avg[0][1])) / (3.1415 * 0.5);
f2 = open('_avg_color_coords_out.txt', 'w+')
f2.write("%s" % str(v))
# k = cv2.waitKey(5) & 0xff
# if k == 27:
# break
#cv2.destroyAllWindows()
#cap.release()
f2.close()
f.close()
os.remove('_avg_color_coords_in.txt')
6) 38ms : Same as #5 except begin by resizing the canvas by 50% (acceptable loss) which doesn't seem to speed up things at all, and even seems counterproductive a little bit.
Is there a faster way or is this optimal? This will run every second on a 900mhz Rpi, so it needs to be quick. I think 30ms on a 900mhz CPU will be around 150-200ms (not tested yet, waiting for the camera to ship)
I had a quick go in php-vips:
#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
use Jcupitt\Vips;
$image = Vips\Image::newFromFile($argv[1], ['access' => 'sequential']);
# Target colour in RGB.
$target = [50, 10, 100];
# Select pixels where all bands are less than 10 away from the target.
# (and render it to memory ... we'll be reusing this mask image).
# The mask image will have one band with 0 for false and 255 for true.
$mask = $image->subtract($target)->abs()->less(10)->bandand()->copyMemory();
# The number of set pixels in the mask.
$n_set = $mask->avg() * $mask->width * $mask->height / 255;
# Handy for debugging: uncomment to write the mask image for inspection.
# $mask->writeToFile("x.png");
# Make a two-band image where band 0 is x coordinates and band 1 is y
# coordinates.
$coords = Vips\Image::xyz($mask->width, $mask->height);
# Make an indexed histogram: sum $coords at each position.
$pos = $coords->hist_find_indexed($mask);
# fetch the sum of the 255 value (true) pixels
[$x_sum, $y_sum] = $pos->getpoint(255, 0);
echo("x = " . $x_sum / $n_set . "\n");
echo("y = " . $y_sum / $n_set . "\n");
I can run it like this:
$ time ./locate-rgb.php ~/pics/x.jpg
x = 483.375
y = 487.75
real 0m0.079s
user 0m0.085s
sys 0m0.022s
So about 80ms on this modest laptop. That includes PHP startup and shutdown, and decompressing the JPG image.
That's only going to work in very constrained lighting and camera setups, but perhaps that's OK? It would be easy to make the ball detection fancier, but of course it would slow it down a bit.

Convert Gigabytes to Bytes

I am in the position where I am trying to convert gigabytes to bytes from a submit form. I have searched around and I am unable to find anything suitable.
Currently when converting bytes to gigabytes I use this method, which works perfectly.
public function byteFormat($bytes, $unit = "", $decimals = 2)
{
$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4,
'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
$value = 0;
if ($bytes > 0) {
// Generate automatic prefix by bytes
// If wrong prefix given
if (!array_key_exists($unit, $units)) {
$pow = floor(log($bytes)/log(1024));
$unit = array_search($pow, $units);
}
// Calculate byte value by prefix
$value = ($bytes/pow(1024,floor($units[$unit])));
}
// If decimals is not numeric or decimals is less than 0
// then set default value
if (!is_numeric($decimals) || $decimals < 0) {
$decimals = 2;
}
// Format output
return sprintf('%.' . $decimals . 'f '.$unit, $value);
}
There seems to be plenty of examples of bytes to other formats but not the other way around.
I have seen that I can convert the number 1.5 like so
round(($number[0] * 1073741824));
The result is 12992276070, however, when using the byteformat method shown above, I get the following 1610612736, this seems quite a difference between the two methods.
Can anyone suggest a more stable method for converting gigabytes to bytes.
Well there are two different unit symbol, decimal and binary.
As you can see here, decimal multiplication is by 1000 and binary by 1024.
so if you are using "B"(byte), just do something like:
$bytenumber=$giga*pow(1024,3);
if using "b"(bit) :
$bitnumber=$giga*pow(1000,3);
P.S:$giga is your giga number.
You can only get as accurate of a conversion as there are numbers after the decimal place. If you start with 1.29634 gigs you'll get a closer representation to it's actual byte value versus calling it 1.3 Gigs. Is that what you're after?
numberOfBytes = round (numberOfGb * 1073741824)
is the exact answer to your question. It seems, you have miscalculated. Try to check it on a calculator.
The other problem is that if you have the source number of 2 digits, it is incorrect to give an answer in more or less than 2 digits. The correct counting will be:
source: 1.5GB
counting: 1.5GB*1073741824 B/GB= 1610612736 B
rounding to the last significant digit: 1610612736 B ~= 1.6e9 B
answer: 1.6e9 B
But, of course, many clients do not really want the correct answer, they want THEIR answer. It is up to you to choose.

PHP spin system. The lower the number is, the more rewards you get

Okay I have kind of a spin system, you spin and it generates a random number.
If the number is less than 100, you will win.
But how can I make it so, the lower the number his, the higher coins you will get
Currently i have this:
public function getPrize($number)
{
$prize = $number * 250 / 2;
if ($number < 100)
{
return '<span style="color: green;">You have won lucky <b>'.$prize.'</b> coins!</span>';
}
else
{
return '<span style="color: red;">Sorry but, bad luck. You have won nothing! number: '.$number.'</span>';
}
}
$prize is the prize. Basically now I am multi piling it by 250 and dividing by 2. so if I get the number '1'. i will get an awful prize.
How do I do that?
Solved it with a little of thinking and calculation.
1000 - 250 / 100 = 7.5
$prize = 250 + (750 - ($number * 7.5));
Results:
x(1) = 1000
x(100) = 250
Here is one way. Just takes the opposite of the number using a maximum.
function getNumPrizes($number)
{
$maxPrizes = 100;
// using max so we dont get less than 0
$prizesWon = max(($maxPrizes - $number) + 1, 0);
return $prizesWon;
}
This way you'll end up getting 100 coins for a 1, 99 for a 2, etc.
You could then run $prizesWon through another function to scale it how you wish.
Here is another solution.
function getNumPrizes($number)
{
$maxPrizes = 100;
$multiplier = // number you want to multiply with the result. It may be 125 or something else
// using max so we dont get less than 0
$prizesWon = max(($maxPrizes - $number) + 1, 0)*$multiplier;
return $prizesWon;
}
Maybe you'll try this way:
public function getPrize($number)
{
$quad = $number*$number;
if ($number<100 && $number>0)
{
$prize = 0.0525665*$quad-12.885*$number + 1012.83; //http://www.wolframalpha.com/input/?i=quadratic+fit+%281%2C1000%29%2C%2850%2C500%29%2C%28100%2C250%29
return '<span style="color: green;">You have won lucky <b>'.$prize.'</b> coins!</span>';
}
else
{
return '<span style="color: red;">Sorry but, bad luck. You have won nothing! number: '.$number.'</span>';
}
}
edit.
I've found a function which gives the expected results for the given numbers. Hope it's ok.
Data source: Wolphram Alpha
Final version:
if($number < 100){
$prize = round((99.00 - floatval($number)) * 7.653) + 250;
else{
$prize = 0;
}
This gives 250 for $number = 99 and 1000 for $number = 1 as author desires.
you are trying to define a math function f(x) where f(1) = 250 and f(99) = 1000;
there are lots of possible shapes which will.
i suggest you graph the results of your functions to help you decide what is best for you.
here are some examples.
// linear growth
// this produces a straight line
function prize($number) return (101 - number) * 75 + 250;
// log growth
// this produces a log curve where you have diminishing returns
function prize($number) return (log(101 - number) -1 ) * 750 + 250;
// exp growth
// this returns exponential returns
function prize($number) return (((101-number)^2)/10000) * 750 +250;
the basic operations here are you have a function which generates a values for the series between 1-100.
invert the input (101-number) so that smaller inputs produce bigger results.
map the output to your scale... which is between (0 to 750) by multipling 750 by a ratio.
translate your scaled number to 250 which is your minimum

Random Float between 0 and 1 in PHP

How does one generate a random float between 0 and 1 in PHP?
I'm looking for the PHP's equivalent to Java's Math.random().
You may use the standard function: lcg_value().
Here's another function given on the rand() docs:
// auxiliary function
// returns random number with flat distribution from 0 to 1
function random_0_1()
{
return (float)rand() / (float)getrandmax();
}
Example from documentation :
function random_float ($min,$max) {
return ($min+lcg_value()*(abs($max-$min)));
}
rand(0,1000)/1000 returns:
0.348 0.716 0.251 0.459 0.893 0.867 0.058 0.955 0.644 0.246 0.292
or use a bigger number if you want more digits after decimal point
class SomeHelper
{
/**
* Generate random float number.
*
* #param float|int $min
* #param float|int $max
* #return float
*/
public static function rand($min = 0, $max = 1)
{
return ($min + ($max - $min) * (mt_rand() / mt_getrandmax()));
}
}
update:
forget this answer it doesnt work wit php -v > 5.3
What about
floatVal('0.'.rand(1, 9));
?
this works perfect for me, and it´s not only for 0 - 1 for example between 1.0 - 15.0
floatVal(rand(1, 15).'.'.rand(1, 9));
function mt_rand_float($min, $max, $countZero = '0') {
$countZero = +('1'.$countZero);
$min = floor($min*$countZero);
$max = floor($max*$countZero);
$rand = mt_rand($min, $max) / $countZero;
return $rand;
}
example:
echo mt_rand_float(0, 1);
result: 0.2
echo mt_rand_float(3.2, 3.23, '000');
result: 3.219
echo mt_rand_float(1, 5, '00');
result: 4.52
echo mt_rand_float(0.56789, 1, '00');
result: 0.69
$random_number = rand(1,10).".".rand(1,9);
function frand($min, $max, $decimals = 0) {
$scale = pow(10, $decimals);
return mt_rand($min * $scale, $max * $scale) / $scale;
}
echo "frand(0, 10, 2) = " . frand(0, 10, 2) . "\n";
This question asks for a value from 0 to 1. For most mathematical purposes this is usually invalid albeit to the smallest possible degree. The standard distribution by convention is 0 >= N < 1. You should consider if you really want something inclusive of 1.
Many things that do this absent minded have a one in a couple billion result of an anomalous result. This becomes obvious if you think about performing the operation backwards.
(int)(random_float() * 10) would return a value from 0 to 9 with an equal chance of each value. If in one in a billion times it can return 1 then very rarely it will return 10 instead.
Some people would fix this after the fact (to decide that 10 should be 9). Multiplying it by 2 should give around a ~50% chance of 0 or 1 but will also have a ~0.000000000465% chance of returning a 2 like in Bender's dream.
Saying 0 to 1 as a float might be a bit like mistakenly saying 0 to 10 instead of 0 to 9 as ints when you want ten values starting at zero. In this case because of the broad range of possible float values then it's more like accidentally saying 0 to 1000000000 instead of 0 to 999999999.
With 64bit it's exceedingly rare to overflow but in this case some random functions are 32bit internally so it's not no implausible for that one in two and a half billion chance to occur.
The standard solutions would instead want to be like this:
mt_rand() / (getrandmax() + 1)
There can also be small usually insignificant differences in distribution, for example between 0 to 9 then you might find 0 is slightly more likely than 9 due to precision but this will typically be in the billionth or so and is not as severe as the above issue because the above issue can produce an invalid unexpected out of bounds figure for a calculation that would otherwise be flawless.
Java's Math.random will also never produce a value of 1. Some of this comes from that it is a mouthful to explain specifically what it does. It returns a value from 0 to less than one. It's Zeno's arrow, it never reaches 1. This isn't something someone would conventionally say. Instead people tend to say between 0 and 1 or from 0 to 1 but those are false.
This is somewhat a source of amusement in bug reports. For example, any PHP code using lcg_value without consideration for this may glitch approximately one in a couple billion times if it holds true to its documentation but that makes it painfully difficult to faithfully reproduce.
This kind of off by one error is one of the common sources of "Just turn it off and on again." issues typically encountered in embedded devices.
Solution for PHP 7. Generates random number in [0,1). i.e. includes 0 and excludes 1.
function random_float() {
return random_int(0, 2**53-1) / (2**53);
}
Thanks to Nommyde in the comments for pointing out my bug.
>>> number_format((2**53-1)/2**53,100)
=> "0.9999999999999998889776975374843459576368331909179687500000000000000000000000000000000000000000000000"
>>> number_format((2**53)/(2**53+1),100)
=> "1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
Most answers are using mt_rand. However, mt_getrandmax() usually returns only 2147483647. That means you only have 31 bits of information, while a double has a mantissa with 52 bits, which means there is a density of at least 2^53 for the numbers between 0 and 1.
This more complicated approach will get you a finer distribution:
function rand_754_01() {
// Generate 64 random bits (8 bytes)
$entropy = openssl_random_pseudo_bytes(8);
// Create a string of 12 '0' bits and 52 '1' bits.
$x = 0x000FFFFFFFFFFFFF;
$first12 = pack("Q", $x);
// Set the first 12 bits to 0 in the random string.
$y = $entropy & $first12;
// Now set the first 12 bits to be 0[exponent], where exponent is randomly chosen between 1 and 1022.
// Here $e has a probability of 0.5 to be 1022, 0.25 to be 1021, etc.
$e = 1022;
while($e > 1) {
if(mt_rand(0,1) == 0) {
break;
} else {
--$e;
}
}
// Pack the exponent properly (add four '0' bits behind it and 49 more in front)
$z = "\0\0\0\0\0\0" . pack("S", $e << 4);
// Now convert to a double.
return unpack("d", $y | $z)[1];
}
Please note that the above code only works on 64-bit machines with a Litte-Endian byte order and Intel-style IEEE754 representation. (x64-compatible computers will have this). Unfortunately PHP does not allow bit-shifting past int32-sized boundaries, so you have to write a separate function for Big-Endian.
You should replace this line:
$z = "\0\0\0\0\0\0" . pack("S", $e << 4);
with its big-endian counterpart:
$z = pack("S", $e << 4) . "\0\0\0\0\0\0";
The difference is only notable when the function is called a large amount of times: 10^9 or more.
Testing if this works
It should be obvious that the mantissa follows a nice uniform distribution approximation, but it's less obvious that a sum of a large amount of such distributions (each with cumulatively halved chance and amplitude) is uniform.
Running:
function randomNumbers() {
$f = 0.0;
for($i = 0; $i < 1000000; ++$i) {
$f += \math::rand_754_01();
}
echo $f / 1000000;
}
Produces an output of 0.49999928273099 (or a similar number close to 0.5).
I found the answer on PHP.net
<?php
function randomFloat($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
var_dump(randomFloat());
var_dump(randomFloat(2, 20));
?>
float(0.91601131712832)
float(16.511210331931)
So you could do
randomFloat(0,1);
or simple
mt_rand() / mt_getrandmax() * 1;
what about:
echo (float)('0.' . rand(0,99999));
would probably work fine... hope it helps you.

Limiting Number of Digits in PHP

I'm displaying how large a list of files are in a table using PHP. I'd like to display how big they are in megabytes instead of the default bytes. The problem I'm having is that I get extremely long decimals, which is impractical for this purpose.
Here's what I have so far:
print((filesize("../uploads/" . $dirArray[$index])) * .000000953674316 . " MB");
Which correctly converts the value, but changes, for example, 71 B to 6.7710876436E-5 MB.
I think the E-5 thing is like x10^-5 which would probably add up correctly, but is there a way I can cut off how many numbers it goes down to? If it displays as "00.00 MB" that's fine by me, most file are going to be much bigger than this test one.
You can format numbers with the number_format() function.
Edit: the manual page contains a user comment you may like: http://es.php.net/manual/en/function.number-format.php#72969
With good old printf :
printf("%.2f MB",filesize("../uploads/" . $dirArray[$index]) * .000000953674316);
Maybe, because it's a bit clearer what the intention is:
printf("%.2f MB",filesize("../uploads/" . $dirArray[$index]) / (1024 * 1024));
number_format() is good, and don't forget that round() can round the number to any precision you want.
Here is simple nice function: Quick PHP
If you need other units, too, you might use this function I wrote years ago:
<?php
function human_filesize($size, $precision = 2)
{
$a_size = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
$count = count($a_size) - 1;
$i = 0;
while ($size / 1024 >= 1 && $count >= $i) {
$size = $size / 1024;
$i++;
}
return round($size, $precision) . ' ' . $a_size[$i];
}
// =========
// USAGE
// =========
// Output: 34.35 MiB
echo human_filesize(filesize('file.zip'));
// Output: 34 MiB
echo human_filesize(filesize('file.zip'), 0);
// Output: 34.35465 MiB
echo human_filesize(filesize('file.zip'), 5);
?>

Categories