Search code examples
phpscale

scaling a set of numbers down within boundaries


i dont know if this is the right place to ask this question but here it goes I am primarily working in php but an ans in any language will do.

i am making a tag cloud for a website. Something like this

lets say i have an array of numbers

array(54, 67, 68, 72, 98, 103, 112, 136, 169, 200, 201)

this numbers represent how many times a word has been searched for in the website.

in the tag cloud i want to display popular keywords in a bigger font size. So i want to use this numbers as a link to the font size

So my question is, how can i reduce these numbers relatively to each other so that all of them occur with the rage on 10 to 20. Where 10 and 20 will be the font size of the tags

I hope i was clear enough.


Solution

  • Here is the fiddle.

    <?php
    
    $values = array(54, 67, 68, 72, 98, 103, 112, 136, 169, 200, 201);
    
    $max = max($values);
    $min = min($values);
    
    $fontMin = 10;
    $fontMax = 20;
    
    $valueDiff = $max - $min;
    $fontDiff = $fontMax - $fontMin;
    $incrementEvery = round($valueDiff / $fontDiff);
    
    foreach ($values as $value) {
        $actualFont = round(($value - $min) / $incrementEvery) + $fontMin;
        echo "$value: $actualFont \n";
    }
    

    Results in:

    54: 10 
    67: 11 
    68: 11 
    72: 11 
    98: 13 
    103: 13 
    112: 14 
    136: 15 
    169: 18 
    200: 20 
    201: 20
    

    The one-liner is:

    round(($value - $min) / round(($max - $min) / ($fontMax - $fontMin))) + $fontMin;