www.webdeveloper.com
Results 1 to 6 of 6

Thread: Adding Numeric Values in PHP

  1. #1
    Join Date
    Aug 2006
    Posts
    19

    Adding Numeric Values in PHP

    I am attempting to add values that I am pulling from an array. Here is a really simple example.

    $newAr = Array(200000, 300000, 400000, 600000);
    $newArCount = count($newAr);
    for($i=0; $i<$newArCount; $i++)
    {
    $getValue .= + $newAr[$i];
    }

    I am not getting the expected results. I want to add these values to equal a final numeric sum. I tried using the setype() function and still had no luck. Any help would be appreciated.

    Thanks

  2. #2
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,742
    Code:
    $newAr = Array(200000, 300000, 400000, 600000);
    $newArCount = count($newAr);
    for($i=0; $i<$newArCount; $i++)
    {
         $getValue += $newAr[$i];
    }
    Personally I think I would use array_sum().

  3. #3
    Join Date
    Aug 2006
    Posts
    19
    Thanks for that info. What if I wanted to get the average of all those numbers? Thanks again for your help.

  4. #4
    Join Date
    Dec 2006
    Location
    Escaz˙ (Costa Rica) and Mallorca (Spain)
    Posts
    3,234
    Use array_sum().

    If you must loop through the array, then this way:
    PHP Code:
    <?php
    $newAr 
    = Array(200000300000400000600000);
    $getValue 0;
    FOREACH (
    $newAr as $key => $value) :
      
    $getValue += $value;
    ENDFOREACH;
    ?>

  5. #5
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,742
    PHP Code:
    $average array_sum($newAr)/count(($newAr)); 

  6. #6
    Join Date
    May 2011
    Location
    beautiful earth
    Posts
    1

    Thumbs up found the right function for calculating sum of values

    Quote Originally Posted by bokeh View Post
    Code:
    $newAr = Array(200000, 300000, 400000, 600000);
    $newArCount = count($newAr);
    for($i=0; $i<$newArCount; $i++)
    {
         $getValue += $newAr[$i];
    }
    Personally I think I would use array_sum().
    i was searching for this function in wrong places, finally i got your help thanks man...
    you really saved my day...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles