PHP trend / forecast function.

In Excel, there is a useful TREND function which allows you to forecast or estimate future values.

This type of calculation can be extremely helpful if you are generating graphs and statistics.

For a while, we attempted to implement something similar in PHP, to no avail. It turns out that estimating future values is a lot more complicated than you would expect.

Least Squares.

Excel’s TREND function uses the “Least Squares” method, which will be pretty daunting to implement yourself. Thankfully, a machine library called “PHP-ML” exists and it will do the calculations for you.

Firstly, you will need to download the PHP MLX library. Note that at the time of writing, this library required PHP version 7.1 or above. If you’re still on PHP version 5.x at this stage, we highly suggest that you bite the bullet and upgrade. Not only are you missing out on huge performance improvements, you’re also missing out on new libraries like this.

Once you have downloaded PHP ML via composer, you can use the LeastSquares object like so.

use Phpml\Regression\LeastSquares;

$x = [[1], [2], [3], [4], [5], [6]];
$y = [1, 3, 5, 6, 8, 10];

$regression = new LeastSquares();
$regression->train($x, $y);
echo $regression->predict([7]);

In the example above, we provided the $x and $y values of 1 – 6. We then asked the LeastSquares object to predict what 7 will be.

If you run the code snippet above, you will see that the Least Squares object will return “11.6”.