I have an array $prices = array();
. This array contains a number of entries that show a price.
For example € 2.500
My goal is to add all this values and have the average number. But first, to have the € 2.500
in the format of 2500
This is what I know and it is done by using
preg_replace('/[^0-9]/i', '', $variable);
What is a way to accomplish this?
Thank you
You can use array_map
to apply that regex to each element.
$avg = array_sum(array_map(function($v){
return preg_replace('/[^0-9]/i', '', $v);
}, $prices)) / count($prices);
$total = 0;
foreach ($prices as $index => $value)
$total += preg_replace('/[^0-9]/i', '', $value);
echo "€" . number_format($total);
function getCleanArray($prices)
{
$pricesCleaned = array();
foreach ($prices as $value)
{
$pricesCleaned.push(preg_replace('/[^0-9]/i', '', $value));
}
return $pricesCleaned;
}
After this method call you will get array with numbers which you can manipulate further.