Case 1. Semantic search over text documents (no DB)
Implementation in pure PHP
In this case we build a minimal semantic search in PHP: documents are transformed into embeddings, saved into a simple JSON index, and then ranked by cosine similarity to the query. This demonstrates the core engineering cycle (indexing -> query embedding -> similarity search -> top-N results) without a database or vector store.
Example of use
<?php
include 'code-en.php';
$query = 'How to add artificial intelligence to a PHP application?';
$result = $embedder($query, normalize: true, pooling: 'mean');
$queryEmbedding = array_map(static fn ($v): float => (float) $v, $result[0]);
$scored = [];
foreach ($documents as $document) {
$scored[] = [
'score' => cosineSimilarity($queryEmbedding, $document['embedding']),
'document' => $document,
];
}
usort($scored, static fn (array $a, array $b): int => $b['score'] <=> $a['score']);
$topResults = array_slice($scored, 0, 3);
echo 'Query: ' . $query . PHP_EOL . PHP_EOL;
if (count($topResults) === 0) {
echo 'No results found.' . PHP_EOL;
return;
}
foreach ($topResults as $row) {
$score = number_format((float) $row['score'], 2, '.', '');
$document = $row['document'];
echo '[' . $score . '] ' . $document['id'] . PHP_EOL;
echo (string) $document['text'] . PHP_EOL . PHP_EOL;
}
Result:
Memory: 0.001 Mb
Time running: < 0.001 sec.
Query: How to add artificial intelligence to a PHP application?
[0.71] php-ai.md
PHP is gradually becoming part of AI infrastructure.
Developers use PHP to build applications
with language models and intelligent features.
[0.36] machine-learning.txt
Machine learning helps build models
that detect patterns in data
and improve search and recommendation quality.
[0.33] laravel.md
Laravel is used to build
modern web applications.