0

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.

2 Answers 2

3

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); 
Sign up to request clarification or add additional context in comments.

Comments

1

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   
}

?>

1 Comment

$totalCost is never declared as 0 before the looped addition assignment combined operator is used -- this will make PHP complain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.