I have an associative array with 15 different companies and their stock prices, formatted as shown below:
$CloseStockPrice ('Business'=>50.5. 'Business two'=>100.5, .....)
I have found the average stock price:
$Average = (array_sum($CloseStockPrice)/count($CloseStockPrice));
The average ends up being 161.
But I now need to find the closest number (absolute terms) to that average value (161) within the associative array. I need to display the business and the stock value.
My most recent attempt:
function computeClosest(array $CloseStockPrice)
{
$closest = 161;
for ($i = 161; $i < count($CloseStockPrice) ; $i++)
{
if ($closest === 161)
{
$closest = $CloseStockPrice[$i];
} else if ($CloseStockPrice[$i] > 161 && $CloseStockPrice[$i] <= abs($closest))
{
$closest = $CloseStockPrice[$i];
} else if ($CloseStockPrice[$i] < 161 && -$CloseStockPrice[$i] < abs($closest))
{
$closest = $CloseStockPrice[$i];
return $closest;
}
}
}
Any suggestions?