Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hanscode44/e8c2557b83c4f4658f583e230ecd5836 to your computer and use it in GitHub Desktop.
Save hanscode44/e8c2557b83c4f4658f583e230ecd5836 to your computer and use it in GitHub Desktop.
Creating an array for histogram
<?php
$data = array(
164, 150, 132, 144, 125, 149, 145, 146,
158, 140, 147, 136, 148, 152, 144, 168,
126, 138, 176, 163, 119, 154, 165, 146,
173, 142, 147, 135, 153, 140, 135, 161,
145, 135, 142, 150, 156, 145, 128, 157
);
$maxBins = 0; // if no maximum bins needed set to 0.
$maxRangePerBin = 10; // if no range per bin needed, set to 0.
$min = min($data);
$max = max($data);
$labels = [];
$res = [];
if ($maxRangePerBin > 0) {
$expectedBins = ceil(($max - $min) / $maxRangePerBin);
$valuePerBin = $maxRangePerBin;
} else {
$maxBins = $maxBins > 0 ? $maxBins : 10; // if no maximum number of bins set, set maxBins to 10.
$valuePerBin = ceil(($max - $min) / $maxBins);
$expectedBins = $maxBins;
}
if ($maxBins > 0) {
$totalBins = $maxBins;
} else {
$totalBins = $expectedBins;
}
sort($data);
for ($i = 0; $i < $totalBins; $i++) {
$count = 0;
if ($maxBins > 0 && $i == $totalBins - 1) {
foreach ($data as $key => $number) {
$count++;
unset($data[$key]);
}
} else {
foreach ($data as $key => $number) {
if ($number <= (($min + ($valuePerBin - 1)) + ($i * $valuePerBin))) {
$count++;
unset($data[$key]);
}
}
}
if ($maxBins > 0 && $i == $totalBins - 1 && $maxRangePerBin != 0) {
if ($count > 0) {
$labels[$i] = ">= " . ($min + ($i * $valuePerBin));
$res[$i] = $count;
}
} else if (count($data) > 0 || $count > 0) {
$res[$i] = $count;
$labels[$i] = ($min + ($i * $valuePerBin)) . '-' . (($min + ($valuePerBin - 1)) + ($i * $valuePerBin));
}
}
var_dump(array("labels" => $labels, "values" => $res));
// Output when maxBins = 0 and maxRangePerBin = 10:
// 119-128 => 4
// 129-138 => 6
// 139-148 => 14
// 149-158 => 9
// 159-168 => 5
// 169-178 => 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment