user3478609
user3478609

Reputation: 65

Sum values while looping

I'm having troubles calculating the total value from an array. I'm not sure how to access it. Below is my code:

if (file_exists('data.txt')) {
    $result = file('data.txt');
    foreach ($result as $value) {
        $columns = explode('!', $value);          
        echo '<tr>
            <td>' . $columns[0] . '</td>
            <td>' . $columns[1] . '</td>
            <td>' . $columns[2] . ' лв.</td>
            <td>' . $type[trim($columns[3])] . '</td>
            </tr>';
        $cost = (float) $columns[2];
    
        $totalCost = array($cost);
        var_dump($totalCost);
    }
}
?>

var_dump($cost) results in:

float(2.5) float(35) float(2.5) float(20)

and var_dump($totalCost):

array(1) { [0]=> float(2.5) }
array(1) { [0]=> float(35) }
array(1) { [0]=> float(2.5) }
array(1) { [0]=> float(20) }

I need to get the total value of the floats inside $cost.

Upvotes: 0

Views: 110

Answers (2)

Vinod Bhatia
Vinod Bhatia

Reputation: 111

Your code should be

<?php
if(file_exists('data.txt')){
    $result=  file('data.txt');
    foreach ($result as $value) {
        $columns=  explode('!', $value);          
        echo '<tr>
            <td>'.$columns[0].'</td>
            <td>'.$columns[1].'</td>
            <td>'.$columns[2].' лв.</td>
            <td>'.$type[trim($columns[3])].'</td>
            </tr>';
        $totalCost +=(float)$columns[2];
    }
     echo $totalCost; // This will give you total value   
}

?>

Upvotes: 1

Amal Murali
Amal Murali

Reputation: 76656

Keep adding the costs into an array and calculate the sum after the loop iteration:

$costs = array();

foreach ($result as $value) {
    $columns=  explode('!', $value);   

    echo '<tr>
        <td>'.$columns[0].'</td>
        <td>'.$columns[1].'</td>
        <td>'.$columns[2].' лв.</td>
        <td>'.$type[trim($columns[3])].'</td>
        </tr>';

    $costs[] = (float) $columns[2];
}

$totalCost = array_sum($costs); 

Upvotes: 3

Related Questions