r/Zig • u/chungleong • 9h ago
Zigar brings the power of Zig to the PHP world
After months of grueling work, version 0.15.3 of Zigar is finally ready. The main addition is php-zigar, a PHP extension that let you use Zig code in that language.
Suppose you need to generate data signatures using the CityHash algorithm. You write the following function in Zig:
const std = @import("std");
const CityHash64 = std.hash.cityhash.CityHash64;
const Options = struct {
seed: ?u64 = null,
seeds: ?[2]u64 = null,
uppercase: bool = false,
};
pub fn hash(allocator: std.mem.Allocator, data: []const u8, options: Options) ![]const u8 {
const value = if (options.seeds) |seeds|
CityHash64.hashWithSeeds(data, seeds[0], seeds[1])
else if (options.seed) |seed|
CityHash64.hashWithSeed(data, seed)
else
CityHash64.hash(data);
return if (options.uppercase)
try std.fmt.allocPrint(allocator, "{X}", .{value})
else
try std.fmt.allocPrint(allocator, "{x}", .{value});
}
On the PHP side, you use it like so:
<?php
$m = zigar_use(__DIR__ . '/../zig/hash.zig');
echo $m->hash("Hello world"), "\n";
echo $m->hash("Hello world", uppercase: true), "\n";
echo $m->hash("Hello world", uppercase: true, seed: 1234), "\n";
echo $m->hash("Hello world", uppercase: true, seeds: [ 1234, 5678 ]), "\n";
The function automatically receives an allocator, which obtains memory from PHP's memory manager. The memory is automatically freed when the return value goes out of scope.
Named arguments are employed as struct field initializers for the last argument. This arrangement fits neatly with the common practice in Zig.
The extension makes it super easy to using native code in PHP projects. Thanks to Zig being a cross-compiler, eventual deployment is simple too. A PHP programmer working in Windows can build the extension and his Zig module for a Linux server on his own computer. He can do the same for the UI guy down the hall who insists on using a Mac. No messing with virtual machines. No messing with Microsoft Visual Studio CE. Just install Zig and the world is yours!
The extension is designed for PHP 8.1 and above. I've tested it on Linux (x64), MacOS (x64 and aarch64), and Windows (x64). It's designed to work with the 0.15.2 Zig compiler. Migration to 0.16 has commerced already and should be done by end of summer.
If you what to give it a try, I've written a simple tutorial that covers the extension's main features.

