Converting bytes to short name in PHP

Sometimes we need to display bytes in more human readable form. Using this function you can easily convert 10 000 000 bytes to 9.54 Mb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
 * @param int $bytes
 * @param null $unit
 * @return string
 */

function byteConvert($bytes, $unit = null)
{
    //Array of latin unit names
    $unitNames = array('b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb', 'Vb');

    //Is working unit defined
    if(!is_null($unit))
    {
        //make sure that unit is in correct format
        $unit = ucfirst(strtolower($unit));

        //check we know such unit
        if(!in_array($unit, $unitNames))
            $unit = null;
    }

    //are we using custom units?
    if(is_null($unit))
    {
        //get fraction of bytes
        $fraction = log($bytes) / log(1024);

        //How many units do we know
        $knownUnits = count($unitNames);

        //is unit out of known range?
        if ($fraction > $knownUnits)
        {
            $num = $knownUnits;

            $unit = $unitNames[$knownUnits - 1];
        }
        else
        {
            $num = floor($fraction);

            $unit = $unitNames[$num];
        }
    }
    else
    {
        $num = array_search($unit, $unitNames);
    }

    return sprintf('%.2f %s', ($bytes / pow(1024, $num)), $unit);
}

Leave a Reply