I'm having troubles calculating the total value from an array. I'm not sure how to access it. Bellow is my code:
<?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>';
$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. Any help would be appreciated.
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);
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
}
?>