The code below gets a list of all the .csv files in a directory. I have created the function csvcolumnsum to extract some information from each file (the sum of all values in column 3) and inject it within each list item.
The html output should look something like this:
<li>Filename (sum)</li>
But it comes out like this:
sum<li>Filename ()</li>
Can anyone point out why this is happening? Here is the relevant code.
require("csvcolumnsum.php");
echo "<ul class=\"users\">";
$handle=opendir("data");
while (($file = readdir($handle))!==false) {
$file = preg_replace("/\\.[^.\\s]{3}$/","",$file);
if (preg_match('/[^\.]/i', $file)) {
$value = csvcolumnsum("data/".$file.".csv",3);
echo "<li><a href=\"?form_name=$file\">$file(";
echo $value;
echo ")</a></li>";
}
}
closedir($handle);
echo "</ul>";
csvcolumnsum.php
function csvcolumnsum($filename,$col) {
$handle2 = fopen($filename, 'r');
$data = fgetcsv($handle2);
foreach ($data as $headercolumn) {}
while ($data = fgetcsv($handle2)) {
$sum += $data[$col];
}
echo "<span>$sum</span>";
fclose($handle2);
}
That isn’t how
echoworks. If your want your function to communicate a value back to the calling function, your function needs toreturnthe value, notechoit:Echo writes directly to the standard output, meaning this line:
prints before these lines:
Returning halts execution in the current function, meaning your
closewill need to occur before yourreturn: