ITellMyselfSecrets's avatar

Human readable byte size

Hi,

It's question X for today! Thank you all for helping me out.

I currently list some uploaded files but I want to show the filesize which is readable. I have the bytes stored in the database but I just need to ouput them correctly. How can I do that?

0 likes
2 replies
bobbybouwmann's avatar
Level 88

It's fun helping you out! Keep up with the questions!

Something like this should do for you!

public static function bytesToHuman($bytes)
{
    $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];

    for ($i = 0; $bytes > 1024; $i++) {
        $bytes /= 1024;
    }

    return round($bytes, 2) . ' ' . $units[$i];
}

Please or to participate in this conversation.