Want to forecast future sales using your own code? Learn how to build a simple yet powerful PHP function that predicts future values based on historical sales data — just like Excel’s FORECAST.LINEAR! No external libraries needed.
- Month 8: €25,242.86
- Month 9: €26,239.29
- Month 10: €27,235.71
Want to predict your own sales in PHP?
Get the complete code, step-by-step guide, and learn how to make your own forecast
Need help with something more advanced, like multi-variable forecasting or integration with your database?
Contact me — I can help you build it!
This is the PHP code you can register in your theme’s functions.php file and this is the shortcode
you should add to your post :
// Forecast sales
function forecast_sales_shortcode($atts) {
// Default attributes (you can override in the shortcode)
$atts = shortcode_atts([
‘months’ => ‘1,2,3,4,5,6,7’,
‘sales’ => ‘18500,20000,18000,22000,23000,23500,23800’,
‘forecast’ => ‘8,9,10’
], $atts);
$months = array_map(‘intval’, explode(‘,’, $atts[‘months’]));
$sales = array_map(‘floatval’, explode(‘,’, $atts[‘sales’]));
$futureMonths = array_map(‘intval’, explode(‘,’, $atts[‘forecast’]));
// Forecast function
$forecasted = forecastLinearBatch($months, $sales, $futureMonths);
// Generate output
$output = “<ul>”;
foreach ($forecasted as $month => $value) {
$output .= “<li><strong>Month $month:</strong> €” . number_format($value, 2) . “</li>”;
}
$output .= “</ul>”;
return $output;
}
// Helper function
function forecastLinearBatch($knownXs, $knownYs, $forecastXs) {
$n = count($knownXs);
$sumX = array_sum($knownXs);
$sumY = array_sum($knownYs);
$sumXY = $sumXX = 0;
for ($i = 0; $i < $n; $i++) {
$sumXY += $knownXs[$i] * $knownYs[$i];
$sumXX += $knownXs[$i] * $knownXs[$i];
}
$slope = ($n * $sumXY – $sumX * $sumY) / ($n * $sumXX – $sumX ** 2);
$intercept = ($sumY – $slope * $sumX) / $n;
$results = [];
foreach ($forecastXs as $x) {
$results[$x] = $slope * $x + $intercept;
}
return $results;
}
add_shortcode(‘forecast_sales’, ‘forecast_sales_shortcode’);
View also

Comments are closed.