Finding Euclidean Distance in PHP

This is a simple but powerful function which can be used to find the euclidean distance.

function eucDistance(array $a, array $b) {
            function($x, $y) {
                return abs($x - $y) ** 2;
            }, $a, $b
    ) ** (1/2);
// now use it with any array
// make sure both arrays have the same number of elements
echo eucDistance([1,2,5,6,4.6], [4,6,33,45,2.5]);

How it works is, we send the two arrays to the eucDistance() function as $a and $b. The array_map() function is used to get an array of each element which is the square of the difference between two corresponding elements in $a and $b. Then, we sum all the values. The square root of the sum is retuned.

Tagged: PHP Algorithms Machine Learning
Written By
Supun Kavinda
Written On
Apr 17, 2019
Last Updated On
Apr 17, 2019
Latest on Hyvor Developer
Creating a Real-Time Chat App with PHP and Node.js
All About MYSQLI Prepared Statements in PHP
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
PHP Contact Form - The Email Method
Related Articles