Sparkline from Numbers Using Unicode Blocks
PHP Code Editor
Execution Result
Ready to execute
Click the "Run Script" button to see the output here
Description
Sometimes you want a sense of a trend without a real chart, a tiny inline graphic you can drop into a log line, a CLI dashboard, or a status email. Sparklines do exactly that by mapping each number in a series to one of eight Unicode block characters of increasing height, so a row of them sketches the shape of the data in the width of a word.
The function finds the minimum and maximum of the series, normalizes each value to a fraction of that range, and scales the fraction to an index from zero to seven to pick a block. The only edge case is a flat series where every value is equal, which has zero range and would divide by zero, so that collapses to the lowest block. Everything is plain string work with built-in min and max.
function sparkline(array $values): string {
$ticks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
$min = min($values);
$max = max($values);
$range = $max - $min;
$out = '';
foreach ($values as $value) {
$index = $range > 0
? (int) round(($value - $min) / $range * (count($ticks) - 1))
: 0;
$out .= $ticks[$index];
}
return $out;
}
echo sparkline([3, 5, 9, 6, 2, 8, 7, 10, 4]) . "\n";
echo sparkline([1, 1, 1, 1]) . "\n"; // flat series
Comments
No comments yet
Be the first to share your thoughts!