Turning this into a function (Beginner Level)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jason

    Turning this into a function (Beginner Level)

    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.

    Thanks,
    J

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

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

    #2
    Re: Turning this into a function (Beginner Level)

    Jason wrote:
    [snip]

    function votepercent($vo tes, $totalvotes) {
    $total = round(($votes/$totalvotes)*10 0);
    return $total;
    }

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

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

    Comment

    • Pedro Graca

      #3
      Re: Turning this into a function (Beginner Level)

      Jason wrote:[color=blue]
      > 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.[/color]
      [snip]

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


      <?php
      function calc_percentage s($individual_v otes) {
      $sum = array_sum($indi vidual_votes);
      foreach ($individual_vo tes as $k=>$v) {
      $ret[$k] = round($v/$sum*100);
      }
      return $ret;
      }

      /* example usage */

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

      $percs = calc_percentage s($votes);
      print_r($percs) ;
      ?>

      --
      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. |

      Comment

      • Jason

        #4
        Re: Turning this into a function (Beginner Level)

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

        Comment

        Working...