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.
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.
$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% )
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With