Skip to content
Volume P · The TensorCore.si Library

PHP

The language that runs much of the web.

PHP powers WordPress, which runs over 40% of websites, plus Wikipedia and Laravel apps. Modern PHP 8 is fast and typed, and it can call LLM APIs to add AI features to millions of existing sites.

Prologue

Why learn PHP?

PHP is easy to deploy on almost any web host, and knowing it lets you customise WordPress, build Laravel apps and add AI features to existing sites.

  • Everywhere on the web: WordPress, WooCommerce, Drupal and Laravel.
  • Easy hosting: almost every web host runs PHP out of the box.
  • AI for websites: call LLM APIs to add chatbots, summaries and search.
Prologue

Set up and run your first program

Install PHP 8.2+ (or use a local stack such as Laragon or MAMP) and Composer for packages.

terminal
php -v
php hello.php
php -S localhost:8000   # built-in web server
hello.php
<?php
$name = "Ada";
echo "Hello, AI! Welcome to PHP, $name.\n";
TipFiles start with <?php. Variables always start with $.
Chapter 1

Variables and types

Variables start with $. PHP 8 supports type declarations for parameters, return values and properties, and strict mode with declare(strict_types=1).

variables.php
<?php
declare(strict_types=1);
$layers = 32;
$lr = 3e-4;
$model = "llama3.1";
$params = 8_030_000_000;
printf("%s: %d layers, FP16 %.1f GB\n", $model, $layers, $params * 2 / 1e9);
var_dump($lr);
Chapter 2

Control flow and match

if, for, foreach and while work as expected. The match expression is a stricter, shorter switch that returns a value.

control.php
<?php
foreach (["H100", "B200"] as $i => $gpu) {
    echo "$i: $gpu\n";
}
$bits = 8;
$name = match ($bits) {
    32 => "FP32",
    16 => "FP16",
    8 => "FP8",
    default => "other",
};
echo $name, "\n";
Chapter 3

Arrays

PHP arrays are both lists and dictionaries. Functions like array_filter, array_map and usort transform them.

arrays.php
<?php
$vram = ["H100" => 80, "H200" => 141, "B200" => 180];
$big = array_keys(array_filter($vram, fn($gb) => $gb > 100));
print_r($big);
$doubled = array_map(fn($gb) => $gb * 2, $vram);
echo json_encode($doubled), "\n";
Chapter 4

Classes and enums

Classes support constructor property promotion, readonly properties and interfaces. Enums give named constant sets.

classes.php
<?php
enum Precision: string { case FP16 = "fp16"; case FP8 = "fp8"; }
final class Gpu {
    public function __construct(
        public readonly string $name,
        public readonly int $vramGb,
    ) {}
    public function fits(float $gb): bool { return $gb <= $this->vramGb; }
}
$g = new Gpu("RTX 5090", 32);
echo $g->name, " fits 16 GB: ", var_export($g->fits(16), true), " ", Precision::FP8->value, "\n";
Chapter 5

Handling web requests and JSON

PHP shines at the web. $_GET, $_POST and php://input hold request data; json_encode and json_decode handle JSON APIs.

api.php
<?php
// api.php  →  run: php -S localhost:8000, then open /api.php?name=Ada
header("Content-Type: application/json");
$name = $_GET["name"] ?? "world";
$body = json_decode(file_get_contents("php://input") ?: "{}", true);
echo json_encode(["greeting" => "Hello, $name", "received" => $body]);
Part II · AI with PHP

AI with PHP

PHP is not used to train models, but it is ideal for bringing AI into websites: chatbots, content generation, semantic search and moderation in WordPress and Laravel apps, all by calling model APIs.

The essential libraries

openai-php/clientA popular OpenAI-compatible client.
PrismA Laravel package for LLMs, tools and structured output.
LLPhantRAG, embeddings and agents in PHP.
Rubix MLClassic machine learning in pure PHP.

Gradient descent from scratch

Learn y = 3x + 0.5 with loops.

gradient.php
<?php
$n = 100; $xs = []; $ys = [];
for ($i = 0; $i < $n; $i++) {
    $x = -1 + 2 * $i / ($n - 1);
    $xs[] = $x;
    $ys[] = 3 * $x + 0.5 + (mt_rand() / mt_getrandmax() - 0.5) * 0.2;
}
$w = 0.0; $b = 0.0; $lr = 0.1;
for ($step = 0; $step < 500; $step++) {
    $gw = 0; $gb = 0;
    foreach ($xs as $i => $x) {
        $err = $w * $x + $b - $ys[$i];
        $gw += 2 * $err * $x / $n; $gb += 2 * $err / $n;
    }
    $w -= $lr * $gw; $b -= $lr * $gb;
}
printf("w=%.2f b=%.2f\n", $w, $b);
Part III · Build an AI agent

Build an AI agent in PHP

With PHP's built-in cURL and JSON functions you can run the full tool-calling loop against a local model in Ollama.

Your goal→Model plans→Tool call→Your code runs the tool→Result back to model→Final answer
agent.php
<?php
function chat(array $body): array {
    $ch = curl_init("http://localhost:11434/v1/chat/completions");
    curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ["Content-Type: application/json"], CURLOPT_POSTFIELDS => json_encode($body)]);
    $res = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $res;
}
$tools = [["type" => "function", "function" => ["name" => "get_weather", "description" => "Weather for a city",
    "parameters" => ["type" => "object", "properties" => ["city" => ["type" => "string"]], "required" => ["city"]]]]];
$messages = [["role" => "user", "content" => "Should I take an umbrella in Lahore today?"]];

for ($round = 0; $round < 5; $round++) {
    $msg = chat(["model" => "llama3.1", "messages" => $messages, "tools" => $tools])["choices"][0]["message"];
    $messages[] = $msg;
    if (empty($msg["tool_calls"])) { echo $msg["content"], "\n"; break; }
    foreach ($msg["tool_calls"] as $call) {
        $args = json_decode($call["function"]["arguments"], true);
        $messages[] = ["role" => "tool", "tool_call_id" => $call["id"], "content" => "It is 24°C and sunny in {$args["city"]}."];
    }
}

In Laravel, the Prism package wraps this loop with tools defined as PHP classes or closures.

Run it locallyInstall Ollama, run ollama pull llama3.1, and keep it running. The code talks to its OpenAI-compatible API at http://localhost:11434/v1, so the same program also works with vLLM, llama.cpp server or a cloud API by changing the URL, model name and adding an API key.
Part IV · Your path

PHP learning roadmap

Tick items off as you go. Your progress is saved in this browser.

Beginner

Intermediate

Advanced

Part IV · Your path

Projects to build

Contact formValidate input and store it with PDO.
WordPress AI pluginGenerate post summaries with an LLM.
Laravel chatbotA support bot that answers from your docs.
Reference

PHP cheat sheet

TaskSyntax
Printecho "Hi $name";
Array$a = [1, 2, 3];
Map$m = ["k" => "v"];
Arrow fnfn($x) => $x * 2
Classclass P { public function __construct(public int $x) {} }
JSONjson_encode($data)
Reference

Common mistakes

  • Building SQL with string concatenation allows SQL injection; use PDO prepared statements.
  • == does loose comparison; prefer ===.
  • Echoing user input without htmlspecialchars allows XSS.
Reference

Where to go next

On TensorCore.si: JavaScript volume, How AI works.

Keyboard: [ previous language · ] next language · / search the library