Created
December 15, 2022 15:02
-
-
Save relipse/005612e965de426794c79edfbaa0077f to your computer and use it in GitHub Desktop.
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 | |
$opts = getopt('s:f:h', ['file:','string:','help']); | |
var_dump($opts); | |
$helpstr = <<<EOD | |
Description: Sum all the values given in either the file or string. | |
Usage: php {$argv[0]} OPTIONS | |
OPTIONS | |
-s, --string String of numbers to sum | |
-f, --file File to load and sum | |
-h, --help Show this help message | |
EOD; | |
$string = $opts['string'] ?? $opts['s'] ?? ''; | |
$file = $opts['file'] ?? $opts['f'] ?? null; | |
if (empty($file) && empty($string)){ | |
die("Nothing to sum. \n".$helpstr); | |
} | |
if (empty($string)){ | |
if (!file_exists($file)){ | |
die("File does not exist: $file. Nothing to sum.\n$helpstr"); | |
} | |
$string = file_get_contents($file); | |
if (empty($string)){ | |
die("File is empty. Nothing to sum.\n$helpstr"); | |
} | |
} | |
if (preg_match_all('/\$((\d+),?(\d+)\.\d+)/', $string, $matches) >= 1){ | |
$sum = 0; | |
$count = 0; | |
$max = 0; | |
$min = null; | |
$avg = null; | |
foreach($matches[1] as $i => $match){ | |
$value = floatval(str_replace(',','',$match)); | |
if (empty($value)){ | |
continue; | |
} | |
echo '$'.number_format($value, 2)."\n"; | |
if ($value > $max){ | |
$max = $value; | |
} | |
if (is_null($min) || $value < $min){ | |
$min = $value; | |
} | |
$sum += $value; | |
$count++; | |
} | |
$avg = $sum/$count; | |
echo "\n".$count.' entries.'."\n". | |
' => '.'$'.number_format($sum, 2)."\n". | |
"Max: $".number_format($max, 2)."\n". | |
"Min: $".number_format($min, 2)."\n". | |
"Avg: $".number_format($avg, 2)."\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment