Embedding as a vector of numbers (PHP)

Minimal example: embedding as a vector of numbers (PHP)

Below is a minimal pure PHP example where we emulate embeddings with fixed vectors and compare a query against documents using cosine similarity. This is the core semantic-search mechanic without external libraries.d

Example of code:

 
<?php

function embed(string $text): array {
    return match (
$text) {
        
'speed up email sending' => [0.120.880.340.56],
        
'email newsletter optimization' => [0.100.850.300.60],
        
'how to prepare coffee' => [0.910.050.120.02],
        default => [
0.00.00.00.0],
    };
}

function 
cosineSimilarity(array $a, array $b): float {
    
$dot 0.0;
    
$normA 0.0;
    
$normB 0.0;

    foreach (
$a as $i => $value) {
        
$dot += $value $b[$i];
        
$normA += $value ** 2;
        
$normB += $b[$i] ** 2;
    }

    if (
$normA == 0.0 || $normB == 0.0) {
        return 
0.0;
    }

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