Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $files = [];
- // Get each line of input representing a file.
- while($line = fgets(STDIN)) {
- $parts = explode("\t", trim($line));
- $files[] = [
- 'size' => $parts[0],
- 'name' => $parts[1],
- ];
- }
- // Sort the files by their size in descending order
- usort($files, function ($first, $second) {
- return $second['size'] <=> $first['size'];
- });
- $maxLength = 0;
- // Format the file size with comma as thousands separator
- // and find the maximum size length.
- foreach($files as $i => &$file) {
- $file['size'] = number_format($file['size'] * 1024);
- $length = strlen($file['size']);
- if($length > $maxLength) {
- $maxLength = $length;
- }
- }
- // Deallocate the $file variable reference to prevent unexpected behaviour.
- unset($file);
- // Align the size to the right by adding leading spaces and print the output.
- foreach($files as $i => $file) {
- $size = str_pad($file['size'], $maxLength, ' ', STR_PAD_LEFT);
- echo "$size {$file['name']}\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement