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.12, 0.88, 0.34, 0.56],
'email newsletter optimization' => [0.10, 0.85, 0.30, 0.60],
'how to prepare coffee' => [0.91, 0.05, 0.12, 0.02],
default => [0.0, 0.0, 0.0, 0.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));
}