PHP Bytesize : Number Grouping

Recently I’ve been toying with helper methods and classes for analysing certain types of data and came up with a real simple way of calculating numerical groupings – given a step and a set of values. Let’s say you have a list of numbers, such as the following…


$arr = [4, 3, 5, 10, 21, 22, 26];

Now imagine you want to bracket these into the following groupings for statistical analysis…


$result = [

'1 - 5' => 3,

'5 - 10' => 1,

'20 - 25' => 1,

'25 - 30' => 1

];

We could iterate over each of the values in the initial array and figure out where it sits, but our loop will get pretty messy pretty quickly.

Doesn’t this feel like a very self contained operation? We could call this function – groupNumeric

This will take a value, and a step for our grouping…


function groupNumeric($value, $step) 
{
    // How many steps are in value
    // So say we had 21, and we were grouping in 5's
    // 21/5 = 4.2, cast as an INT is 4
    $multiples = ((int) ($value/$step));
    // Take our rounded down value, and multiply it by the steps
    // 4 * 5 = 20 
    $lower = $multiples * $step;
    // Add 1 on to the multiplier, and multiply it by the steps
    // (4 + 1) * 5 = 25
    $upper = ($multiples + 1) * $step;
    return "$lower - $upper";
}

To use this all we need to do is pass every element of the initial array to this function.

$result = [];
// loop across the values in our array
foreach ($value in $arr) {
    // get the grouping string
    $grouping = groupNumeric($value, 5);
    // if it's not set in the result as a key
    // then set it
    if (!isset($result[$grouping)) {
        $result[$grouping] = 0;
    }
    // increment the corresponding grouping value
    $result[$grouping]++;
}

Handy eh? Now go forth and group, whether it’s ages, scores, amount of Pringles eaten before popping = stopping.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s