Advertisement
Guest User

format-du-output

a guest
Dec 13th, 2017
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.00 KB | None | 0 0
  1. <?php
  2.  
  3. $files = [];
  4.  
  5. // Get each line of input representing a file.
  6. while($line = fgets(STDIN)) {
  7.     $parts = explode("\t", trim($line));
  8.  
  9.     $files[] = [
  10.         'size' => $parts[0],
  11.         'name' => $parts[1],
  12.     ];
  13. }
  14.  
  15. // Sort the files by their size in descending order
  16. usort($files, function ($first, $second) {
  17.     return $second['size'] <=> $first['size'];
  18. });
  19.  
  20. $maxLength = 0;
  21.  
  22. // Format the file size with comma as thousands separator
  23. // and find the maximum size length.
  24. foreach($files as $i => &$file) {
  25.     $file['size'] = number_format($file['size'] * 1024);
  26.  
  27.     $length = strlen($file['size']);
  28.     if($length > $maxLength) {
  29.         $maxLength = $length;
  30.     }
  31. }
  32. // Deallocate the $file variable reference to prevent unexpected behaviour.
  33. unset($file);
  34.  
  35. // Align the size to the right by adding leading spaces and print the output.
  36. foreach($files as $i => $file) {
  37.     $size = str_pad($file['size'], $maxLength, ' ', STR_PAD_LEFT);
  38.     echo "$size {$file['name']}\n";
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement