Add numbers in array

Discussion in 'PHP' started by MajHate, Aug 10, 2009.

  1. #1
    Hello,

    Let's stay I have an array with only numbers. How can I add them up so I have them in one variable. So like I can have:

    $total_value_of_array

    Thank You!
     
    MajHate, Aug 10, 2009 IP
  2. XDMCoder

    XDMCoder Peon

    Messages:
    50
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    <?php
    $numArray = array(1,2,3,4,5,6);
    $total_value_of_array = "";
    foreach($numArray as $x)
    {
    	$total_value_of_array.=$x;
    }
    echo ($total_value_of_array);
    ?>
    PHP:
     
    XDMCoder, Aug 10, 2009 IP
  3. MajHate

    MajHate Member

    Messages:
    48
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    that does not do anything, it just lists numbers 1 through 6.

    also, what if i did not no the number of numbers there were going to be, not just a set number of keys
     
    MajHate, Aug 10, 2009 IP
  4. XDMCoder

    XDMCoder Peon

    Messages:
    50
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I dont understand you...
    You have an array of numbers. By foreach you get all your array variables in one variable. If you want sum of this variables:
    <?php
    $numArray = array(1,2,3,4,5,6);
    $total_value_of_array = 0;
    foreach($numArray as $x)
    {
        $total_value_of_array+=$x;
    }
    echo ($total_value_of_array);
    ?>
    PHP:
     
    XDMCoder, Aug 10, 2009 IP
  5. livedating

    livedating Active Member

    Messages:
    161
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    83
    #5
    You can also use these alternatives:
    
    $ar = array(3,4,6,2,6,4,24,3,34,32,19);
    
    // #1 - join
    $str1 = join('.', $ar);
    // split('.', $ar) to decode back to array
    
    // #2 - serialize
    $str2 = serialize($ar);
    // unserialize($str2) to decode
    
    // #3 - json
    $str3 = json_encode($ar);
    // json_decode($str3) to decode
    
    
    Code (markup):
     
    livedating, Aug 12, 2009 IP
  6. kblessinggr

    kblessinggr Peon

    Messages:
    539
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Would be so much easier if you just did this.

    $sum = array_sum($array_name);

    the function array_sum calculates the sum of all the values in an array. All this splitting, looping etc is a waste of lines.
     
    kblessinggr, Aug 12, 2009 IP