Last active
October 7, 2023 11:25
-
-
Save nagiyevelchin/24692312cdb915d60ff767bc33dcf7d2 to your computer and use it in GitHub Desktop.
This PHP function takes a number of bytes as input and converts it into a human-readable format with units like KB, MB, GB, or TB, depending on the magnitude of the input. The precision parameter allows you to control the number of decimal places in the formatted result. The function is well-commented to explain each step of the process.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Format a given number of bytes into a human-readable string with specified precision. | |
* | |
* @param int|float $bytes The number of bytes to format. | |
* @param int $precision The number of decimal places for precision (default is 2). | |
* | |
* @return string The formatted string representing the bytes with appropriate units (e.g., KB, MB, GB). | |
*/ | |
function formatBytes($bytes, $precision = 2) { | |
// Define an array of unit labels for different byte magnitudes. | |
$units = ['B', 'KB', 'MB', 'GB', 'TB']; | |
// Ensure $bytes is non-negative. | |
$bytes = max($bytes, 0); | |
// Calculate the appropriate unit index based on the magnitude of $bytes. | |
$pow = floor(($bytes ? log($bytes) : 0) / log(1024)); | |
// Ensure the unit index does not exceed the available units. | |
$pow = min($pow, count($units) - 1); | |
// Calculate the size in the appropriate unit. | |
$bytes /= pow(1024, $pow); | |
// Round the result to the specified precision and append the unit label. | |
return round($bytes, $precision) . ' ' . $units[$pow]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment