Turning this into a function (Beginner Level)

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I need some help writing the following lines of code into a simple
function. I'd like to be able to create a function to do the
calculation, then feed the $a, $b, or $c variable into it.


<?php $a = $kerryvotes/$votes;
      $kpercentage = $a * 100;
      $kpercent = round($kpercentage, 0);  

<?php $b = $bushvotes/$votes;
      $bpercentage = $b * 100;
      $bpercent = round($bpercentage, 0);  
<?php $c = $nadervotes/$votes;
      $npercentage = $c * 100;
      $npercent = round($npercentage, 0);  

Re: Turning this into a function (Beginner Level)

Jason wrote:
Quoted text here. Click to load it

You needn't do it one by one ...
Here's a function to do it all in one swoop :-)

function calc_percentages($individual_votes) {
  $sum = array_sum($individual_votes);
  foreach ($individual_votes as $k=>$v) {
    $ret[$k] = round($v/$sum*100);
  return $ret;

/* example usage */

/* disclaimer: the numbers are random */
$votes = array('bush'=>555, 'kerry'=>555, 'nader'=>555);

$percs = calc_percentages($votes);

USENET would be a better place if everybody read:    | to  mail  me:  simply |
http://www.catb.org/~esr/faqs/smart-questions.html    | "reply" to this post, |
http://www.netmeister.org/news/learn2quote2.html      | *NO* MIME, plain text |
http://www.expita.com/nomime.html                     | and *NO* attachments. |

Re: Turning this into a function (Beginner Level)

Jason wrote:

function votepercent($votes, $totalvotes) {
    $total = round(($votes/$totalvotes)*100);
    return $total;

Use example:
echo 'Kerry has yer '.votepercent($quantityforkerry, $totalofvotes).' %
of the votes';

"La demande mondiale d’ordinateurs n’excédera pas cinq machines."
(Thomas Watson, Fondateur d'IBM, 1945)

Re: Turning this into a function (Beginner Level)

thanks, this looks good.. i'll try both methods..

Site Timeline