Add numbers from a loop?

Discussion in 'PHP' started by MrLeN, Mar 26, 2011.

  1. #1
    I have this code:

    
    if ($handle = opendir($referrals_url)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $file = ereg_replace('.php','', $file);
                echo count($_SESSION[''.$file.'_filecount']);
            }
        }
        closedir($handle);
    }
    
    Code (markup):
    It all works fine. It is reading a directory and getting a number (that is associated with the directory) from a session.

    Currently there are 3 folders with 3 numbers. 1, 5 and 7

    How do I add those numbers together, so that the above code doesn't output: 157?

    I want it to add them and output: 13.
     
    MrLeN, Mar 26, 2011 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #2
    
    $sum = 0;
    settype($sum, "integer");
    if ($handle = opendir($referrals_url)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $file = ereg_replace('.php','', $file);
                echo count($_SESSION[''.$file.'_filecount']);
                $sum = $sum + count($_SESSION[''.$file.'_filecount']);
            }
        }
        closedir($handle);
    }
    
    echo $sum;
    
    PHP:
     
    ThePHPMaster, Mar 26, 2011 IP
  3. MrLeN

    MrLeN Well-Known Member

    Messages:
    406
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    120
    #3
    You da man!

    Thanks heaps. I have been trying to work that out for HOURS.

    I was starting to get a bit stroppy :)

    Much appreciated :D
     
    MrLeN, Mar 26, 2011 IP