I’m having a strange problem. I’m trying to get an average of numbers from a table.
I created an array, then imploded it but when I give the value, it only outputs the first number not the average I need.
What am I doing wrong?
<?php
(...)
foreach($lr_loop as $row):
$loc_rate[] = $row["stars"];
endforeach;
$loc_rate_imploded = implode(', ', $loc_rate);
echo $loc_rate_imploded; // Gives 5,2,3,5,4 etc.
$array = array($loc_rate_imploded);
echo "<br><br>";
$avg = array_sum($array) / count($array);
echo $avg; //Only shows the first number, in this case: 5
?>
$loc_rate is the array of values you should be using.
Putting the imploded string into a php array() creates an array of one element consisting of that string. While that produces somethings that ‘looks’ like the syntax definition for creating an array, it’s not because the string of values isn’t php code.
I think the point that @mabismad was making is, you already have an array of all those values, you build it in your foreach() loop right at the start. So why do you need to copy it into $array? (BTW - terrible name for an array).
This line
$array = array_values($loc_rate);
doesn’t really add anything, because (unless your code is a simplified version and there’s more to the full version) your original $locrate array doesn’t have any keys to start with.