In Excel, there is a handy TREND function, which allows you to forecast or estimate future values. This type of calculation can be extremely helpful when generating graphs and whatnot. For a while, I 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.
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 ML 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, I 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 = [, , , , , ]; $y = [1, 3, 5, 6, 8, 10]; $regression = new LeastSquares(); $regression->train($x, $y); echo $regression->predict();
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”.