-1

I have a foreach loop that searches through files and creates arrays for that files and it all works as intended. In the foreach loop I create a $total variable adding a set amount of the values in that loop to each other. I would like to add all of the $total's at the end of my code, which I figure could be achieved by sending each $total automatically to a seperate array outside the loop, and then using an array_sum() function, but I'm struggling. Here is an example of my code -->

<?php

foreach($file as $client) {

    $name = $client;

    $document = "client/" . $name . "";



    $client_data = file_get_contents($document);

    $data = explode("\t",$client_data_);


$total = $data[0] + $data[1] + $data[2] + $data[3];

}

?>

And then of course to send that $total to an array to add together... I have no clue on how to do this... any tips/solutions?

Apologies if this is ignorant, or badly worded.. I'm a student and relatively new to the coding stuff (and want to get good marks).

  • 2
    i think you just want `$total += $data[0] + $data[1] + $data[2] + $data[3];` –  Jul 23 '19 at 05:57
  • and define `$total = 0` before the loop, otherwise, PHP will complain – catcon Jul 23 '19 at 05:59
  • Possible duplicate of [How to add elements to an empty array in PHP?](https://stackoverflow.com/questions/676677/how-to-add-elements-to-an-empty-array-in-php) – yqlim Jul 23 '19 at 05:59
  • quite anti-climactic but does the job! thanks very much - also yes apologies if this had been asked already, i'd looked but nothing seemed to work for me, probabaly my ignorance... thanks for the solve! – Jack Champion Jul 23 '19 at 06:08

2 Answers2

1
$total = 0;

foreach($file as $client) {
    $name = $client;
    $document = "client/" . $name . "";
    $client_data = file_get_contents($document);
    $data = explode("\t",$client_data_);
    $total += $data[0] + $data[1] + $data[2] + $data[3];
}

echo $total;
ni3solanki
  • 502
  • 3
  • 12
1

set a $temporary_total variable to hold the total of the items within the array first, then add it to the $final_total

<?php

$final_total = 0;

foreach($file as $client) {
 $name = $client;
 $document = "client/" . $name . "";
 $client_data = file_get_contents($document);
 $data = explode("\t",$client_data_);
 $temporary_total = $data[0] + $data[1] + $data[2] + $data[3];

 $final_total = $final_total + $temporary_total; //adding your sum of $temporary_total to the $finaltotal

 }

echo $final_total;

?>
Manas
  • 3,060
  • 4
  • 27
  • 55