Euclidean distance, dot product, cosine similarity

Examples of using Euclidean distance, dot product, and cosine similarity.

Three core operations in vector-based ML are Euclidean distance, dot product, and cosine similarity. They answer different questions: how far two vectors are, how strongly they align with weighted coordinates, and how similar their direction is.

In PHP these operations are straightforward to implement and are often used inside ranking, recommendation, classification, and nearest-neighbor logic.

Example of code:

 
<?php

// Euclidean distance between two vectors
function euclideanDistance(array $a, array $b): float {
    
$n count($a);

    if (
$n !== count($b)) {
        throw new 
InvalidArgumentException('Vectors must have the same length');
    }

    
$sum 0.0;

    for (
$i 0$i $n$i++) {
        
$diff $a[$i] - $b[$i];
        
$sum += $diff ** 2;
    }

    return 
sqrt($sum);
}

// Dot product (scalar product) of two vectors
function dotProduct(array $a, array $b): float {
    
$n count($a);

    if (
$n !== count($b)) {
        throw new 
InvalidArgumentException('Vectors must have the same length');
    }

    
$sum 0.0;

    for (
$i 0$i $n$i++) {
        
$sum += $a[$i] * $b[$i];
    }

    return 
$sum;
}

// Cosine similarity based on dot product and vector norms
function cosineSimilarity(array $a, array $b): float {
    
$dot dotProduct($a$b);
    
$normA sqrt(dotProduct($a$a));
    
$normB sqrt(dotProduct($b$b));

    if (
$normA == || $normB == 0) {
        throw new 
InvalidArgumentException('Zero vector');
    }

    return 
$dot / ($normA $normB);
}