I am reading data from file and displaying array like below code :
if (($fp = fopen("test.txt", "r")) !== FALSE) {
$count = 0;
while(($row = fgetcsv($fp)) !== FALSE)
{
$row = explode("|",$row[0]);
foreach($row as &$el)
{
$el=trim($el);
}
$count++;
$tot = array_sum(array_column($row,2));
echo "<pre>";print_r($row);
if($count>3)
{
break;
}
echo "Coumt :".$tot;
}
echo "Coumt :".$tot;
fclose($fp);
}
Test.txt file data :
005-4410040 |BIRM| 0
005-4410040 |CHI | 450
005-4410040 |CIN | 144
I want total sum of 2nd index of the array it means 320 + 450 + 144
in separate varriable.
How can I achieve this? I already tried array_column()
, but its not working.
Update: What I have tried:
$sum = array_sum(array_column($row,$row['2']));
You should be able to achieve that using array_column()
and array_sum()
like this
$row = [
['005-4410040','BIRM',1],
['005-4410040','CHI',2],
['005-4410040','CIN',3]
];
$tot = array_sum(array_column($row, 2));
RESULT
6
You are not understanding fgetcsv()
correctly, it gets one line at a time. So each call to fgetcsv return one line from the file which you explode into $row
All you need to do is accumulate $row[2]
as you process over the lines of the file.
if (($fp = fopen("test.txt", "r")) !== FALSE) {
$count = 0;
$tot = 0;
while(($row = fgetcsv($fp)) !== FALSE)
{
$row = explode("|",$row[0]);
$count++;
// I see one line with no value so to be safe
$tot += $row[2] != '' ? $row[2] : 0;
if($count>3) {
break;
}
echo "Coumt : $tot";
}
echo "Coumt : $tot";
fclose($fp);
}