Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array key values into percentages

Tags:

arrays

php

So i've got an array that looks something like of:

Array ( [Safari] => 13 [Firefox] => 5 )

How do i a make a new array that looks like :

Array ( [Safari] => 72.2% [Firefox] => 27.7% )

using a neat php function?

thanks in advance.

like image 548
Carlos Barbosa Avatar asked May 27 '11 00:05

Carlos Barbosa


3 Answers

You can use array_sum() to get the total, then iterate over the values returning the new value.

$total = array_sum($share);

foreach($share as &$hits) {
   $hits = round($hits / $total * 100, 1) . '%';
}

CodePad.

If you have >= PHP 5.3 it can be a tad more elegant with an anonymous function.

$total = array_sum($share);

$share = array_map(function($hits) use ($total) {
   return round($hits / $total * 100, 1) . '%';
}, $share);

CodePad.

like image 118
alex Avatar answered Nov 06 '22 10:11

alex


    $array=array ( 'Safari' => 13 ,'Firefox' => 5 );
    $tot=array_sum($array);

    foreach($array as $key=>$value){
       $result[$key]=number_format(($value/$total)*100,1).'%';
    }

    print_r($result); //Array ( [Safari] => 72.2% [Firefox] => 27.7% )
like image 31
senthilkumar Avatar answered Nov 06 '22 09:11

senthilkumar


Try this:

$array = Array ( 'Safari' => 13, 'Firefox' => 5 );
$total = array_sum($array); # total sum of all elements
$onePercent = $total / 100; # we want to know what value represents 1 percent
array_walk($array, create_function('&$v', '$v /= '.$onePercent.'; $v .= " %";')); # we walk through the array changing numbers to percents
var_export($array);

If you want to have your result in second array leaving $array not touched, you can use array_map instead of array_walk

You also might want to use sprintf to set precision of float values that represent percent, because my code would output:

array (
  'Safari' => '72.2222222222 %',
  'Firefox' => '27.7777777778 %',
)

It's not hard to figure out how to do it?

like image 40
Nemoden Avatar answered Nov 06 '22 10:11

Nemoden