Converting Bytes To Better Format
Every now and then we need a simple function that could take any number in bytes taken from filesize() or other source and convert it for better reading. Here are some functions that do the exact same thing but with different methods.
Method 1: Very simple straight forward stuff. Can be customized to different sizes with different limits.
1 2 3 4 5 6 7 8 | function convert_size($num) { if ($num >= 1073741824) $num = round($num / 1073741824 * 100) / 100 .' gb'; else if ($num >= 1048576) $num = round($num / 1048576 * 100) / 100 .' mb'; else if ($num >= 1024) $num = round($num / 1024 * 100) / 100 .' kb'; else $num .= ' b'; return $num; } |
Method 2: (best way) More advance using a loop to count size depth. Very small and compact all the way to YB. Unlike method 1 it runs by a single constant.
1 2 3 4 5 6 7 8 9 10 | function convert_size($size){ $i=0; $iec = array(" B", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"); while (($size/1024)>1) { $size=round($size/1024,2); $i++; } return substr($size,0,strpos($size,'.')+4).$iec[$i]; } |
As you see if you wish to have a large range conversion using the first method then you will have lots of IF statements unlike method two. Iif you are using method one you have more simple flexibility to have different off-sets for sizes.
Method two uses a single while loop to take the size to its lowest by every 1024 and each time it loops it reduces a single multiple of 1024 and counts how many times it reduces it, and at the end shows the corresponding unit size from the array using that count. The array must have the unit sizes in correct order. Good thing about this is if you give it a number that is like 7^20 (that’s 20 zeroes), then it still works just fine as long as the array has that many unit sizes.