// PHPLANG — LANGUAGE REFERENCE

phplang v0.2.17 · PHP on fusevm · lex/parse → AST → fusevm bytecode → Cranelift JIT · no bespoke VM · MIT · in active development

Docs GitHub
// Color scheme

>_LANGUAGE REFERENCE

Every reserved keyword, language construct, type cast, and library function the current phplang build recognizes, grouped by keyword then construct then cast then library area. This page is generated from the language corpus (src/lsp.rs) by the gen-docs binary, so it stays in sync with what the runtime actually implements. Keywords/constructs mirror lexer.rs and parser.rs; each library function mirrors a real dispatch arm in src/builtins.rs.

Keyword

# if

if (expr) statement

Conditional branch; runs its body when the condition is truthy. The body is a single statement or a braced block. PHP's alternative `if: … endif;` syntax is not parsed.

if (1 < 2) echo "y";   // => y

# elseif

if (expr) stmt elseif (expr) stmt

Additional condition tested when every preceding one failed. The two-word spelling `else if` is folded into the same branch list by the parser, so both forms behave identically.

if (0) echo "a"; elseif (1) echo "b";   // => b

# else

if (expr) stmt else stmt

Fallback branch taken when the `if` condition and every `elseif` condition are falsey.

if (0) echo "a"; else echo "b";   // => b

# while

while (expr) statement

Loops while the condition stays truthy, testing before each pass. The alternative `while: … endwhile;` syntax is not parsed.

$i = 0; while ($i < 3) $i++; echo $i;   // => 3

# do

do statement while (expr);

Post-tested loop; the body always runs at least once. The trailing `while (…)` and its semicolon are both required.

$i = 5; do $i++; while ($i < 3); echo $i;   // => 6

# for

for (init; cond; step) statement

C-style loop. Each of the three clauses is a comma-separated expression list and each may be empty; an empty condition loops forever.

$s = 0; for ($i = 1; $i <= 3; $i++) $s += $i; echo $s;   // => 6

# foreach

foreach (expr as [&]$value) statement
foreach (expr as $key => [&]$value) statement

Iterates an array. A `&` before the value variable iterates by reference and writes each assignment back into the array. Only arrays and generators are iterable — no user class implements `Iterator`.

foreach ([1, 2] as $v) echo $v;   // => 12

# as

foreach (expr as $v)
use A { m as [visibility] [alias]; }   //  trait adaptation
use Ns\Name as Alias;   //  namespace import

Binds the current element inside a `foreach` header. In a trait adaptation block it binds a trait method under a second name, a new visibility, or both — `m as x;` adds `x` alongside `m`, `m as protected;` only re-marks `m`. In a namespace import it names the alias the imported name is bound to for the rest of the namespace.

foreach ([9] as $k => $v) echo $k;   // => 0

# insteadof

use A, B { A::m insteadof B[, C]; }   //  inside a class body

Resolves a trait method collision by EXCLUDING the named traits' version of the method, inside the `{ … }` block of a `use`. Two used traits declaring the same method with no `insteadof` between them is a fatal error, and excluding only one of three still leaves the other two colliding. The excluded method is not gone — an `as` alias in the same block can still bind it under another name.

trait A { function m() { return "A"; } }
trait B { function m() { return "B"; } }
class C { use A, B { A::m insteadof B; B::m as bm; } }
$c = new C; echo $c->m(), $c->bm();   // => AB

# switch

switch (expr) { case expr: … default: … }

Multi-way branch; each `case` compares against the subject with loose (`==`) equality. A case label may end in `:` or `;`. The alternative `switch: … endswitch;` syntax is not parsed.

switch (2) { case 2: echo "two"; }   // => two

# case

case expr:   //  also: case Name [= value]; inside an enum

A labelled `switch` branch, falling through into the next branch until a `break`. Inside an `enum` body the same keyword declares a case, optionally with a backing value.

switch (1) { case 1: echo "a"; case 2: echo "b"; }   // => ab

# default

default:   //  in switch;   default => expr   //  in match

The branch taken when no case matched — in a `switch` body and in a `match` expression.

switch (9) { default: echo "d"; }   // => d

# break

break;
break <int>;   //  level parsed, then IGNORED

Exits the nearest enclosing loop or `switch`. DIVERGENCE: the optional numeric level is parsed and discarded (`src/parser.rs`), so `break 2;` unwinds ONE level exactly like `break;` instead of two. Nested loops therefore keep running where reference PHP would have left them.

for ($i=0;$i<2;$i++){ for ($j=0;$j<2;$j++){ echo $i.$j." "; break 2; } }
echo "end";   // => 00 10 end   (PHP 8 prints: 00 end)

# continue

continue;
continue <int>;   //  level parsed, then IGNORED

Skips to the next iteration of the nearest loop. DIVERGENCE: like `break`, the numeric level is parsed and discarded, so `continue 2;` only restarts the innermost loop.

foreach ([1, 2, 3] as $v) { if ($v == 2) continue; echo $v; }   // => 13

# declare

declare(directive=value);
declare(directive=value) { body }   //  not for strict_types

Sets a compilation-unit directive. `strict_types=1` turns off the coercion a scalar parameter or return type would otherwise perform, so a value must already be of the declared type — with int→float widening the one exception, since it cannot lose anything. Its rules are all COMPILE-time, and each has its own message: it must be the very first statement (a preceding `declare` does not count against it, any other statement does), its value must be the literal `0` or `1`, and it may not use the block form even though `ticks` may. `ticks` is accepted and ignored — no tick handler exists to call. `encoding` is recognised and refused with the reference's own wording; any other directive warns `Unsupported declare`. DIVERGENCE: upstream reads the mode from the CALLER's file, so a strict file calling a non-strict file's function still checks strictly; phplang has no `include`, so a run is one file and the two readings coincide.

declare(strict_types=1); function f(int $x) { return $x; } f("5");   // => TypeError

# function

function name(params) [: type] { body }
function (params) [use (vars)] [: type] { body }   //  closure

Declares a named function as a statement, or an anonymous closure as an expression. Parameter and return types are ENFORCED — scalars, unions, intersections, class names, `self`/`parent`/`static`, `array`, `iterable`, `callable`, `object`, `mixed`: a scalar is coerced on the way in by default and required exactly under `declare(strict_types=1)`, and a value no part accepts raises `TypeError`. A function with no `return` yields null.

function sq($x) { return $x * $x; } echo sq(4);   // => 16

# fn

fn(params) [: type] => expr

Arrow function: a single-expression body that automatically captures every free variable by value. Returns a real `Closure`.

$d = fn($x) => $x * 2; echo $d(4);   // => 8

# use

function (…) use ($a, $b) { … }
use Ns\Name [as Alias];
use T1, T2 [{ adaptations }];   //  inside a class body

Three unrelated roles. In a closure header it captures the named enclosing variables by value — DIVERGENCE: by-reference capture `use (&$v)` is rejected with a parse error rather than silently binding by value. As a statement it is a namespace import — of a class or namespace, or with `use function` / `use const` of a function or constant — binding an alias (the last segment unless `as` names one) for the rest of the namespace; a second import under the same alias is a compile-time fatal. Inside a class body it pulls the traits' members in, with an optional `{ … }` block of `insteadof`/`as` adaptations resolving collisions and binding extra names.

$n = 10; $f = function () use ($n) { return $n; }; echo $f();   // => 10

# return

return [expr];

Returns a value from the current function, or null when the expression is omitted. At the top level it ends the script.

function one() { return 1; } echo one();   // => 1

# yield

yield;
yield $value;
yield $key => $value;

Suspends the enclosing generator and hands a value (and optionally a key) to the consumer; the expression evaluates to whatever the next `->send()` passes in. Any function containing `yield` becomes a generator, run on its own native stack.

function g() { yield 1; yield 2; } foreach (g() as $v) echo $v;   // => 12

# yield from

yield from expr

Delegates to an inner generator or array, re-yielding each of its elements before continuing.

function inner() { yield 1; yield 2; }
function outer() { yield from inner(); yield 3; }
foreach (outer() as $v) echo $v;   // => 123

# match

match (expr) { cond[, cond] => expr, … , default => expr }

PHP 8 expression that compares the subject to each arm with strict (`===`) equality and evaluates the first hit. With no matching arm and no `default` it throws `UnhandledMatchError` rather than yielding null.

echo match (2) { 1 => "a", 2 => "b" };   // => b
try { echo match (5) { 1 => "a" }; }
catch (UnhandledMatchError $e) { echo $e->getMessage(); }   // => Unhandled match case 5

# array

array(elem, …)   //  identical to [elem, …]

The long-form array literal constructor. It parses to exactly the same node as the `[…]` short form, so keys, `=>` pairs, and destructuring behave identically.

echo count(array(1, 2, 3));   // => 3

# list

list($a, $b) = expr;
list('k' => $v) = expr;

The long-form destructuring target. It desugars to the same array node as `[$a, $b] = …`, so both forms share one assignment path. An empty slot (`list(, $b)`) still consumes a positional index.

list($a, $b) = [1, 2]; echo $a . $b;   // => 12

# clone

clone $object

Duplicates an object: a new instance of the same class carrying a copy of the properties, then `__clone()` on the copy if the class defines one. The copy is shallow the way PHP means it — an array property is a value and travels as a copy, an object property is a handle and stays shared with the original. Binds tighter than every operator, so `clone $a->b` clones the property and `clone $a instanceof C` tests the clone. A non-object is `TypeError: clone(): Argument #1 ($object) must be of type object, int given`; a live generator holds a suspended stack and is refused with `Error: Trying to clone an uncloneable object of class Generator`.

class C { public $n = 1; } $a = new C; $b = clone $a; $b->n = 2; echo $a->n, $b->n;   // => 12

# clone()

clone(object $object, array $withProperties = [])

PHP 8.5 function form of `clone`: the copy is made and `__clone()` runs, then each entry of `$withProperties` is assigned to it from the CALLING scope, so visibility, `__set`, declared types and `private(set)` apply as they would to `$copy->name = $value`, while a `readonly` property may be written once more. Written with a single operand it is the ordinary `clone`, so `clone($a)->m()` still clones the result of `($a)->m()`. Argument unpacking is not supported. Failures carry a `clone(...)` frame: `clone(): Argument #2 ($withProperties) must be of type array`, `clone() expects at least 1 argument, 0 given`. An exception or enum case is refused as uncloneable.

$p = clone(new stdClass, ["a" => 1]); echo $p->a;   // => 1

# class

[abstract|final|readonly] class Name [extends Parent] [implements I, …] { members }

Declares a class: constants, properties, static properties, and methods. `abstract` marks the class un-instantiable; `readonly` makes every property it declares readonly; `final` forbids a subclass (see `final`).

class C { public $x = 1; } $o = new C; echo $o->x;   // => 1

# interface

interface Name [extends I, …] { const …; function m(); }

Declares an interface, stored in the same class table as classes. `interface_exists()` reports it and `class_exists()` does NOT, as in PHP, where each existence predicate answers for one declaration kind.

interface I {} class C implements I {} $o = new C;
var_dump($o instanceof I, interface_exists("I"), class_exists("I"));   // => bool(true) bool(true) bool(false)

# trait

trait Name { members }   //  then: use Name; inside a class

Declares a reusable member bundle that a class pulls in with `use`, optionally adapted by an `insteadof`/`as` block. A `use` naming a trait that was never declared is a throwable `Error`; an unresolved method collision is a fatal raised when the declaration is reached, so output produced before it is still printed. DIVERGENCE: two definitions of the same property with different defaults are merged silently rather than refused.

trait T { function f() { return 3; } } class C { use T; } echo (new C)->f();   // => 3

# enum

enum Name [: backing-type] [implements I] { case A [= value]; … }

Declares an enum. Cases are class constants holding a case object with `->name` and, for a backed enum, `->value`. Every enum implicitly implements `UnitEnum`, and a backed one also `BackedEnum`. `enum` is only treated as a declaration when a name and `{`, `:`, or `implements` follow, so a bareword `enum` still parses as an identifier. An enum answers yes to both `enum_exists()` and `class_exists()`, as in PHP.

enum Suit: string { case Hearts = "H"; } echo Suit::Hearts->value;   // => H

# extends

class C extends Parent    //  interface I extends A, B

Single inheritance for a class — the child inherits its parent's methods, properties, and constants. An interface may extend several parents, which the parser records as implemented interfaces.

class A { function f() { return 1; } } class B extends A {} echo (new B)->f();   // => 1

# implements

class C implements I, J

Lists the interfaces a class satisfies. `instanceof` and `class_implements()` both walk this list transitively, including through parent classes.

interface I {} class C implements I {} var_dump((new C) instanceof I);   // => bool(true)

# new

new ClassName[(args)]
new class[(args)] [extends P] [implements I, …] { members }

Instantiates a class, running `__construct` with the given arguments. The parentheses are optional when there are no arguments. The class name is a bareword — `new $className` is not parsed. `new class` declares the class inline: its arguments come BEFORE the `extends`/`implements` clauses, and the declaration is compiled once, so the same site in a loop yields instances of one class. Its generated name is `Base@anonymous\0<script>:<line>$<n>` — the parent, else the first interface, else `class` — so `get_class` returns a unique string while `var_dump` and diagnostics print the readable head alone.

class C { function __construct($x) { $this->x = $x; } } echo (new C(5))->x;   // => 5

# const

const NAME = expr[, NAME2 = expr2]*;

Declares a constant. Inside a class or interface body it is a class constant, read back through `ClassName::NAME`. At statement level it is a GLOBAL constant, read back as a bareword — the declaration spelling of `define()`, and top-level only, so a function body or an `if` block rejects it the way PHP's grammar does. It is not hoisted: the constant exists from the statement onwards, so a `defined()` above it answers false. Redefining warns and keeps the FIRST value, through either spelling. Several names may be declared in one comma-separated statement, and a later one may read an earlier one.

class A { const K = 7; } echo A::K;   // => 7
const G = 1, H = G + 1; echo H;   // => 2

# static

static $var [= expr];
static function m() { … }
static public $prop;
static::member

Four roles, told apart by what follows. Before a `$variable` in a function body it declares a static local that survives between calls, its initializer evaluated once, on the declaration's first run; in a closure each closure OBJECT has its own copy (a `clone` or `bindTo` copies the current values), and `var_dump` and `getStaticVariables()` list them after the captured variables; before a member it marks it static; as a `::` qualifier it is late static binding; and before `function`/`fn` it makes a CLOSURE static, so it is not bound to the `$this` of the method it was written in and `Closure::bind` refuses to give it one afterwards (warning `Cannot bind an instance to a static closure, this will be an error in PHP 9` and answering null). It keeps that method's class scope, so a private static stays reachable.

class A { static $n = 4; } echo A::$n;   // => 4
$f = static fn($x) => $x + 1; echo $f(1);   // => 2

# public

public $prop;   public function m() { … }   public function __construct(public $x)

Marks a member publicly visible (the default when no visibility keyword is given). In a constructor parameter list it promotes the parameter to a property.

class C { public $x = 2; } echo (new C)->x;   // => 2

# protected

protected $prop;   protected function m() { … }

Marks a member reachable only from the declaring class and its subclasses. Visibility IS enforced: reading, writing or unsetting the property from outside throws a catchable `Error: Cannot access protected property C::$x` — unless the class defines the matching magic method (`__get`, `__set`, `__unset`), which is consulted first and makes the access succeed instead.

class A { protected $x = 1; }
class B extends A { function g() { return $this->x; } }
echo (new B)->g();   // => 1

# private

private $prop;   private function m() { … }

Marks a member reachable only from the declaring class. Enforced for both properties and methods. A property access from outside throws a catchable `Error: Cannot access private property C::$x`, naming the class that DECLARED it, unless the class defines the matching magic method (`__get`, `__set`, `__unset`), which is consulted first. `isset()` never throws here — an unreachable property is simply not set. A method call from outside throws the catchable `Error: Call to private method C::m() from global scope`, and it is raised before the call's ARGUMENTS run — a class with `__call` reaches the catch-all instead, for a private method just as for an absent one. `new` on a class whose constructor is private is refused the same way, before any constructor argument runs: `Error: Call to private K::__construct() from global scope`, naming the class that declared the constructor. Only that class may instantiate it — the static-factory idiom `static function make() { return new static; }`.

class C { private $x = 4; function get() { return $this->x; } }
echo (new C)->get();   // => 4

# readonly

readonly $prop;   function __construct(public readonly $x)   readonly class C

Marks a property writable exactly once. Accepted on a property declaration, on a promoted constructor parameter, and on the class itself (`readonly class`, which applies it to every property the class declares, promoted parameters included); a trait's readonly property stays readonly in the class that uses it. The one write must come from the declaring class or a subclass, so an outside write to a still-uninitialized property is `Error: Cannot modify protected(set) readonly property C::$x from global scope` and every later write anywhere is `Error: Cannot modify readonly property C::$x`. Writing THROUGH the property (`$o->arr[] = 1`) is `Error: Cannot indirectly modify readonly property C::$arr` and `unset()` on an initialized one is `Error: Cannot unset readonly property C::$x`. `__clone` is the single reopening: it may rewrite the copy's readonly properties, which lock again when it returns.

class C { public readonly $x; function __construct() { $this->x = 1; } }
$c = new C; try { $c->x = 2; } catch (Error $e) { echo $e->getMessage(); }
// => Cannot modify readonly property C::$x

# abstract

abstract class C { abstract function m(); }

On a class it marks it un-instantiable. On a method it means the declaration has no body. The reference's compile-time checks apply: an abstract method in a class not itself declared abstract, an abstract method with a body, a private or final abstract method, and a non-abstract method without a body are each a `Fatal error` before anything runs. DIVERGENCE: a concrete subclass that leaves an abstract method unimplemented is not diagnosed, and calling the method returns null.

abstract class A { abstract function f(); } class B extends A { function f() { return 9; } }
echo (new B)->f();   // => 9

# final

final class C { … }   final function m() { … }

A repeated `final`, or `final` together with `abstract`, is the reference's compile-time `Fatal error`. A `final` class cannot be extended, and a `final` method, constant or property cannot be redeclared by a subclass (or, for a constant, by an implementing class): each is the reference's `Fatal error` when the subclass links — before the program runs for an early-bound class, where its declaration runs otherwise — and an overriding method is reported at its own line. `final` on a trait method carries into the class that uses it. The engine's `Exception`/`Error` getters are final, as in PHP. DIVERGENCE: `final` on a private method is accepted without the reference's compile-time `Private methods cannot be final` warning.

final class A {} class B extends A {}
// => Fatal error: Class B cannot extend final class A

# var

var $prop;

The PHP 4 property declaration keyword. Accepted and treated as `public`.

class C { var $x = 5; } echo (new C)->x;   // => 5

# instanceof

expr instanceof ClassName

True when the value is an object whose class is, extends, or implements the named class — the check walks the parent chain and every implemented interface transitively. `Throwable` is special-cased to match both the `Exception` and `Error` roots.

class A {} class B extends A {} var_dump(new B instanceof A);   // => bool(true)

# try

try { body } catch (T [$e]) { … } [finally { … }]

Guards a block. At least one `catch` or a `finally` must follow, matching PHP's own rule.

try { echo "a"; } finally { echo "b"; }   // => ab

# catch

catch (A | B [$e]) { body }

Handles a thrown object whose class matches any type in the `|`-separated union. The bound variable is optional (PHP 8 syntax). A leading `\` and any `Ns\` prefix are folded away, so `\RuntimeException` and `RuntimeException` name the same class.

try { throw new Exception("x"); } catch (Exception $e) { echo $e->getMessage(); }   // => x

# finally

finally { body }

Runs after the `try`/`catch` on every exit path — normal fall-through, `return`, a rethrown exception, `break`, and `continue`.

try { echo "t"; } finally { echo "f"; }   // => tf

# throw

throw expr;   //  also usable as an expression

Raises an exception. It is both a statement and a PHP 8 expression, so `$x ?? throw new E` and `cond ? throw new E : $v` both parse.

try { throw new Exception("boom"); } catch (Exception $e) { echo $e->getMessage(); }   // => boom

# namespace

namespace Name;   //  or  namespace Name { … }

Every name declared after it belongs to `Name` (`A\f`, `A\P`, `A\K`), and every name referred to resolves inside it: a class name through the imports or the namespace, never the global table, while an unqualified function or constant tries the namespace first and the global one second, at run time. The imports of the namespace before it are dropped. The block form runs its body inline; `namespace { }` is the global namespace.

namespace App; function f() { return 1; } echo f();   // => 1

# true

true

The boolean true literal, matched case-insensitively.

echo true ? "y" : "n";   // => y

# false

false

The boolean false literal, matched case-insensitively.

echo false ? "y" : "n";   // => n

# null

null

The null literal — the absent or unset value, matched case-insensitively. Reading an undefined variable or a missing array key also produces it, quietly.

echo null ?? "fallback";   // => fallback

# and

expr and expr

Logical AND that short-circuits. DIVERGENCE: the parser gives it the same binding power as `&&`, whereas PHP puts `and` below assignment — so `$x = true and false;` assigns `false` here and `true` in PHP 8.

echo (true and false) ? "y" : "n";   // => n

# or

expr or expr

Logical OR that short-circuits. It carries the same precedence as `||`, with the same divergence from PHP's low-precedence `or` described under `and`. There is no `xor` — it is not a token the parser recognizes.

echo (false or true) ? "y" : "n";   // => y

# global

global $var[, $var …];

Binds each name to the GLOBAL variable of that name for the rest of the function. It is a reference, not a copy: a write through either side is seen by the other, and a global that does not exist yet is created by the binding. `unset()` on the local breaks the alias and leaves the global alone. Without the declaration the name is an ordinary, unrelated local. At global scope there is no second frame to bind to and the statement does nothing.

$g = 1; function f() { global $g; $g = 2; } f(); echo $g;   // => 2

Language construct

# echo

echo expr[, expr …];   //  also: <?= expr ?>

Writes one or more values to standard output and has no return value. The short echo tag `<?=` is the single-argument form. An object argument is converted through `__toString`, as it is everywhere a value becomes a string.

echo "hi", "!";   // => hi!

# print

print expr;

Writes a single value to standard output. It is an expression that evaluates to `1`, binding looser than assignment, so `$r = print "a";` prints `a` and leaves `1` in `$r`.

print "hi";   // => hi

# include

include expr

Loads, compiles and runs the named file IN THE CURRENT SCOPE — its variables are the includer's, its functions and classes become global — and evaluates to the file's `return` value, or `1`. A bare relative name is looked for in the working directory and then in the including file's directory; `./` and `../` are relative to the working directory. A file that cannot be read warns `Failed to open stream` and `Failed opening … for inclusion` and yields `false`. A syntax error in the file throws `ParseError`. The loaded code names its own file in diagnostics, traces, `__FILE__` and `__DIR__`, and a trace shows it as an `include('…')` frame. DIVERGENCE: `include_path` is `.` — there is no PEAR directory — and a `declare(strict_types=1)` in an included file does not switch its calls to strict mode.

$r = include "config.php";

# include_once

include_once expr

`include`, unless the resolved file has already been loaded (the main script counts), in which case it evaluates to `true` and does nothing.

# require

require expr

`include`, except that a file that cannot be read warns `Failed to open stream` and then throws `Error: Failed opening required '…'`.

require __DIR__ . "/lib.php";

# require_once

require_once expr

`require`, with `include_once`'s repeat rule.

# eval

eval(string $code): mixed

Compiles and runs `$code` (PHP without an opening tag) in the current scope and evaluates to its `return` value, or null. The code is named `<file>(<line>) : eval()'d code` in diagnostics, traces and `__FILE__`, and a syntax error in it throws `ParseError`.

$x = 2; echo eval('return $x * 21;');   // => 42

# exit

exit[(string|int $status = 0)]: never   //  also spelled `die`

Ends the request where it stands. Both the parentheses and the argument are optional, which is what keeps `exit` a construct even though PHP 8.4 also registered it as a callable function (`function_exists("exit")` is true, and `$f = "exit"; $f(3);` works). An INT becomes the process exit status, taken modulo 256 — `exit(300)` leaves 44 and `exit(-1)` leaves 255. A STRING is written to output and the status is 0. A bool or float narrows to int, a float with a fraction raising `Implicit conversion from float … to int loses precision`; an explicit null is deprecated and reads as 0; anything else is a `TypeError`. The unwind is not catchable and does not run a `finally` — `try { exit(5); } finally { echo "fin"; }` prints nothing — but open output buffers are still flushed on the way out.

echo "a"; exit(3);   // => a, exit status 3

# die

die[(string|int $status = 0)]: never

The alternative spelling of `exit`, folded onto it by the scanner: the two are one construct, so a `die()` argument PHP rejects is reported against `exit()` and a syntax error on `die` names the `exit` token. See `exit` for the semantics.

die("bye");   // => bye, exit status 0

# isset

isset($var[, $var …]): bool

True when every argument is set and not null, staying quiet about undefined variables and missing keys — asking is never an error, so even an unreachable private property is simply `false` rather than a fatal. On an OBJECT PROPERTY it consults `__isset` and stops there: it never reads a value, so `isset($o->p)` is true whenever `__isset` says so even if `__get` would answer null.

$a = 1; echo isset($a) ? "y" : "n";   // => y

# empty

empty($var): bool

True when the argument is falsey or unset, raising no notice for an undefined name, so `empty("0")`, `empty([])`, and `empty(null)` are all true. On an OBJECT PROPERTY it sits between `isset` and `??`: it wants a value, but will not read one through `__get` unless `__isset` vouched for the property first. A class with `__get` and no `__isset` is therefore `empty()` without `__get` ever being called, while `$o->p ?? "d"` on that same class does call it.

echo empty(0) ? "y" : "n";   // => y

# unset

unset($var[, $var …]): void

Removes variables, array elements and object properties. Like `isset`, it is a construct rather than a call, so an index path such as `$a[$k]` is unset in place rather than being evaluated to a value first. `unset($o->p)` removes the property outright — a later read of it goes through `__get` as for any property that is not there — or calls `__unset` when the property is unreachable or absent and the class defines one. Unsetting a property that is not there is not an error; unsetting one that is out of reach, with no `__unset` to take it, throws `Error: Cannot access private property C::$p`.

$a = [1, 2]; unset($a[0]); echo count($a);   // => 1

# #[Attr]

#[Name], #[Name(args)], #[Ns\Name] …   //  before a class, function, method, property, class constant, enum case, or parameter

An attribute group: declarative metadata attached to the declaration that follows. It is NOT a comment — `#[` and `#` are different tokens, and lexing `#[Attr] class C {}` as a comment would delete the declaration. Arguments are scanned for bracket balance and discarded, except `#[\Deprecated]`'s literal `message` and `since`: a function or method carrying it raises `Function f() is deprecated[ since S][, M]` (`E_USER_DEPRECATED`) when called, before its arguments are bound. DIVERGENCE: attributes are not reflectable (`ReflectionAttribute` does not exist); only `#[AllowDynamicProperties]` and `#[\Deprecated]` change behaviour.

#[Attr(1)] class C { #[Attr] public $v = 7; } echo (new C)->v;   // => 7

# #[AllowDynamicProperties]

#[AllowDynamicProperties] class C { … }

Opts a class out of the PHP 8.2 `Deprecated: Creation of dynamic property C::$p is deprecated` notice, which otherwise fires the first time a property no class in the chain declares is written. The opt-out is INHERITED by subclasses. `stdClass` is exempt without it, as is any property the class (or an ancestor) declares — including one promoted from a constructor parameter. The name resolves like any class name, so inside a namespace it is written `#[\AllowDynamicProperties]` or imported; an unqualified one there, or `#[Ns\AllowDynamicProperties]`, is a different, inert attribute.

#[AllowDynamicProperties] class C {} $c = new C; $c->x = 1; echo $c->x;   // => 1

# rust { … }

rust { pub extern "C" fn name(args) -> ty { … } }

Inline Rust FFI. The block is lifted out before lexing and replaced with a `__rust_compile(…)` call carrying the base64-encoded body; every `pub extern "C"` function it exports becomes callable from PHP as a bareword. Unique to phplang — reference PHP has no such construct.

rust { pub extern "C" fn add(a: i64, b: i64) -> i64 { a + b } }
echo add(2, 3);   // => 5

# __LINE__

__LINE__: int

The line the constant is WRITTEN on, resolved by the parse rather than looked up at run time. A function reporting `__LINE__` therefore reports where the constant stands inside it, not the line it was called from.

echo __LINE__;   // => 1

# __FILE__

__FILE__: string

The name of the file the code was compiled from. For the main script that is whatever the ENTRY POINT called it: a named file is its resolved path, `php -r` code is `Command line code`, and a script on standard input is `Standard input code`. Code loaded by `include` names its resolved path, and `eval()`'d code `<file>(<line>) : eval()'d code`. It is the same name every diagnostic quotes, so the two can never disagree.

echo __FILE__;   // => Command line code

# __DIR__

__DIR__: string

The directory part of `__FILE__`. Code with no file behind it — `php -r`, or a script on standard input — has no directory to report, and answers the working directory instead, as the reference does.

var_dump(__DIR__ === getcwd());   // => bool(true)

# __FUNCTION__

__FUNCTION__: string

The enclosing function's name, or `""` at file scope. A CLOSURE has no name of its own, so PHP 8.4 builds it one out of the scope the closure was written in: `{closure:<scope>:<line>}`, where the scope is `__FILE__` at file scope, `f()` inside a function, `C::m()` inside a method — and the closure's own name when closures nest, so the two compose.

function g() { echo __FUNCTION__; } g();   // => g

# __CLASS__

__CLASS__: string

The class the code was WRITTEN in, or `""` outside one — so an inherited method reports the class that declared it, not the subclass the call arrived through. Two cases are answered from the running frame instead, because a parse cannot settle them: inside a TRAIT method it is the class that used the trait (one trait, many users), and inside an anonymous class it is the generated `class@anonymous` name `get_class` reports. A named function declared inside a method body belongs to no class and reports `""`.

class C { function m() { echo __CLASS__; } } class D extends C {} (new D)->m();   // => C

# __METHOD__

__METHOD__: string

`Class::method` for a method, and just the name for a free function — there is no `::` half to prepend outside a class. A trait's method reports the TRAIT (`T::tm`) even though `__CLASS__` in the same body reports the using class. Inside a closure it is the closure's name, the same string `__FUNCTION__` gives.

class C { function m() { echo __METHOD__; } } (new C)->m();   // => C::m

# __NAMESPACE__

__NAMESPACE__: string

The enclosing `namespace` declaration in full — `A\B` — and `""` with no declaration or inside `namespace { }`.

namespace A\B; echo __NAMESPACE__;   // => A\B

# __TRAIT__

__TRAIT__: string

The enclosing `trait` declaration's name, and `""` everywhere else — including inside a class that merely USES the trait, once the method is being read as part of that class's own body.

trait T { function t() { echo __TRAIT__; } } class C { use T; } (new C)->t();   // => T

Operator

# $$

$$name
${expr}

A variable VARIABLE: the operand is evaluated and its string value names the variable to read or write, so the name is not known until it runs. `$$x` nests, so `$$$x` is two lookups, and `${expr}` takes any expression. What it names is an ordinary variable — assignable, unsettable, and acceptable where a by-reference parameter wants a location. A quiet context reads through it without the undefined-variable warning.

$a = 5; $n = 'a'; echo $$n, ' ', ${'a'};   // => 5 5

# +

expr + expr   //  binary;   +expr   //  unary

Numeric addition, or array union when BOTH operands are arrays — the left operand's entries win and the right contributes only the keys it lacks. Under PHP 8 a string operand with no numeric prefix (`"g"`, `""`, `" "`) makes the whole operation a `TypeError: Unsupported operand types: string + int`, while one that merely trails garbage (`"5g"`) raises `Warning: A non-numeric value encountered` and continues with its prefix. Operands resolve left before right, so `"5g" + "g"` warns and then throws while `"g" + "5g"` throws without warning.

echo 2 + 3;   // => 5

# -

expr - expr   //  binary;   -expr   //  unary

Numeric subtraction and arithmetic negation. Unary minus binds looser than `**`, so `-2 ** 2` is `-(2 ** 2)`. Both unary signs are multiplications to the engine, which is why `-"g"` and `+"g"` report `Unsupported operand types: string * int`.

echo 7 - 2, " ", -2 ** 2;   // => 5 -4

# *

expr * expr

Numeric multiplication. Integer operands stay integers unless the result overflows into a float.

echo 6 * 7;   // => 42

# /

expr / expr

Division. Two integers that divide exactly yield an integer, otherwise a float. A zero divisor throws a catchable `DivisionByZeroError` with the message `Division by zero`.

echo 7 / 2;   // => 3.5

# %

expr % expr

Integer remainder, taking the sign of the left operand. Both operands are cast to integers first, so `7.5 % 2` is `1`. A zero divisor throws a catchable `DivisionByZeroError` with the message `Modulo by zero`.

echo 7 % 3;   // => 1

# **

expr ** expr

Exponentiation. It is right-associative and binds tighter than unary minus, and its right operand may itself be a unary expression, so `2 ** -1` parses.

echo 2 ** 3 ** 2;   // => 512

# .

expr . expr

String concatenation, casting both operands to strings. DIVERGENCE: it carries the SAME precedence as `+` and `-` (PHP 7 behaviour). PHP 8 lowered `.` below the additive operators, so `"x" . 1 + 2` groups as `("x" . 1) + 2` here and evaluates to `2`, where PHP 8 gives `"x3"`.

echo "a" . "b";   // => ab
echo "x" . 1 + 2;   // => 2   (PHP 8 prints: x3)

# =

target = expr

Assignment, right-associative and itself an expression. Arrays and objects are handles, so assigning one aliases the same storage rather than copying it — a divergence from PHP's copy-on-write arrays.

$a = 5; echo $a;   // => 5

# =&

$target = &expr

Reference binding: the target becomes another name for the same storage cell rather than a copy of its value.

$a = 1; $b = &$a; $b = 9; echo $a;   // => 9

# += -= *= /= %= .= **=

target op= expr

The arithmetic and string compound assignments. Each reads the target, applies the matching binary operator, and stores the result back — including that operator's PHP 8 operand rules, so `$x = "g"; $x += 9;` is a `TypeError` just as `"g" + 9` is.

$x = 10; $x += 5; $x .= "!"; echo $x;   // => 15!

# &= |= ^= <<= >>=

target op= expr

The bitwise compound assignments — AND, OR, XOR, left shift, and right shift applied in place.

$m = 6; $m &= 3; echo $m;   // => 2

# |>

value |> callable

PHP 8.5 pipe: calls the callable on the right with the value on the left, left-associative. It binds tighter than the relational and equality operators and looser than `.`, shifts and arithmetic, so `1 + 2 |> f(...)` pipes the sum and `1 == 1 |> f(...)` compares against `f(1)`. An arrow function on the right must be parenthesized, and a first-class callable `f(...)` adds no frame of its own to a trace.

echo "abc" |> strtoupper(...) |> strrev(...);   // => CBA

# ??=

target ??= expr

Null-coalescing assignment: stores the right-hand value only when the target is null. It desugars to `target ?? (target = expr)`, so a value that is already there is never rewritten — a readonly or `private(set)` property, `__set` and `offsetSet` are left alone — and a sub-expression of the target (`f()` in `$a[f()]`) is evaluated once.

$a = null; $a ??= 5; echo $a;   // => 5

# ==

expr == expr

Loose equality with PHP 8 string/number comparison: a numeric string compares numerically against a number, while a non-numeric string makes the number a string first — so `"abc" == 0` is false.

var_dump("10" == 10, "abc" == 0);   // => bool(true) bool(false)

# !=

expr != expr   //  also spelled <>

Loose inequality — the negation of `==`. The legacy `<>` spelling lexes to the same operator.

var_dump(1 != 2, 1 <> 1);   // => bool(true) bool(false)

# ===

expr === expr

Strict equality: values must share a type and, for arrays and objects, be the same handle. It is also the comparison `match` uses for its arms.

var_dump("10" === 10, 10 === 10);   // => bool(false) bool(true)

# !==

expr !== expr

Strict inequality — the negation of `===`. `isset()` desugars to a chain of these against null.

var_dump("10" !== 10);   // => bool(true)

# < > <= >=

expr < expr   //  and > <= >=

Relational comparison using the same loose rules as `==`: numeric where both sides look numeric, string comparison otherwise.

var_dump(2 < 10, "2" < "10");   // => bool(true) bool(true)

# <=>

expr <=> expr: int

The spaceship operator: `-1`, `0`, or `1` as the left operand sorts before, with, or after the right. It is the natural comparator for `usort`.

echo 10 <=> 3;   // => 1

# && ||

expr && expr   //  expr || expr

Short-circuiting logical AND and OR. The right operand is not evaluated when the left already decides the result. Both yield a real boolean.

var_dump(true && false, false || true);   // => bool(false) bool(true)

# !

!expr: bool

Logical negation of the operand's truthiness. `empty($x)` desugars to exactly this.

var_dump(!0, !"a");   // => bool(true) bool(false)

# & | ^ ~

expr & expr   //  | ^ ;   ~expr

Bitwise AND, OR, XOR, and one's-complement NOT over 64-bit integers. Both operands are cast to integers first. DIVERGENCE: `&`/`|`/`^` do not operate byte-wise on strings.

echo 6 & 3, " ", 6 | 3, " ", 6 ^ 3, " ", ~5;   // => 2 7 5 -6

# << >>

expr << expr   //  expr >> expr

Arithmetic left and right shift on 64-bit integers. A shift count at or beyond 64 yields `0` for `<<` and the sign-fill (`0` or `-1`) for `>>` rather than wrapping.

echo 1 << 4, " ", -16 >> 2;   // => 16 -4

# ++ --

++target   target++   --target   target--

Increment and decrement in prefix and postfix position. The prefix form evaluates to the new value, the postfix form to the old one. They apply to variables, array elements, properties, and static properties.

$i = 5; echo $i++, $i, ++$i;   // => 567

# ?:

cond ? then : else
cond ?: else

The full ternary and the short `?:` (Elvis) form, which yields the condition itself when it is truthy.

echo 1 ? "a" : "b", "" ?: "fallback";   // => afallback

# ??

expr ?? expr

Null coalescing: the right operand is used when the left is null, and it is quiet about undefined variables and missing keys. Right-associative, so a chain falls through left to right.

$a = null; echo $a ?? "d";   // => d

# ->

$object->property   $object->method(args)

Instance member access — property read/write and method call. The member name is a bareword; `$o->$name` is not parsed.

class C { public $x = 1; function f() { return 2; } }
$o = new C; echo $o->x, $o->f();   // => 12

# ?->

$object?->property   $object?->method(args)

Nullsafe member access: yields null instead of raising when the left operand is null, short-circuiting the rest of the chain.

$o = null; var_dump($o?->x);   // => NULL

# ::

Class::CONST   Class::$staticProp   Class::method(args)   Class::class   $cls::CONST

Scope resolution: class constants, static properties, static and parent method calls, and the `::class` name literal. A static property's name may be computed: `A::$$n` reads the property `$n` names, and `A::${expr}` the one `expr` names. A static property can be bound by reference in either direction (`$r = &A::$p`, `A::$p = &$x`). The left side is either a bareword class name — `self`, `parent`, and `static` included — or a dereferenceable expression whose value names the class at run time: a string is the class name, an object contributes its own. A value that is neither is `Error: Class name must be a valid object or a string`, and a string naming nothing is `Error: Class "X" not found`. `::class` is stricter than the rest: it answers for an object only, and refuses even a class-name string with `TypeError: Cannot use "::class" on string`.

class A { const K = 1; static $s = 2; } $c = "A"; echo A::K, $c::$s, (new A)::class;   // => 12A

# []

expr[index]   $array[] = expr

Array and string indexing. A bare `$a[]` on the left of an assignment appends with the next integer key. String indexing is by byte offset and accepts a negative offset counting from the end.

$a = [1, 2]; $a[] = 3; echo $a[2], "abc"[-1];   // => 3c

# ...

f(...$array)   function f(...$rest)   strlen(...)

Four roles for one token: argument unpacking at a call site, unpacking inside an array literal (`[...$a, ...$b]`), a variadic parameter that collects the trailing arguments into an array, and — as the sole argument — PHP 8.1 first-class callable syntax, which builds a real `Closure`. Unpacking drives a Generator or a Traversable as well as an array; anything else raises "Only arrays and Traversables can be unpacked". A string-keyed array unpacked at a CALL binds each entry to the parameter its key NAMES, and a key no parameter carries is `Error: Unknown named parameter $z`.

function sum(...$n) { return array_sum($n); }
echo sum(...[1, 2, 3]);   // => 6
$f = strlen(...); echo $f("abcd");   // => 4

# name:

f(paramName: value)

PHP 8.0 named arguments. An identifier followed by a single `:` inside an argument list binds that argument to the named parameter, so arguments may be supplied out of order.

function f($a, $b = "z") { return "$a$b"; } echo f(b: "q", a: 1);   // => 1q

# @

@expr

The error-suppression operator. The operand is evaluated exactly as it would be without the `@` and only the DIAGNOSTICS it raises are dropped — including the ones raised from inside the functions it calls, so `@preg_match('/[a', $s)` and `@range('ab', 'c')` are silent too. It is NOT an isset-mode read: `@$o->p` calls `__get` (where `isset($o->p)` would ask `__isset`), and it does not swallow an `Error`, so `@$o->privateProp` still throws. Suppression is restored when an exception unwinds out of the expression.

echo @$undefined ?? "quiet";   // => quiet

# \

\Name   Ns\Name

The namespace separator. A leading `\` makes a name fully qualified (`\RuntimeException` is the global class from inside any namespace); without one a qualified name is relative to the current namespace, unless its first segment is an imported alias, so `App\Util\X` written inside `App` is `App\App\Util\X`. A name held in a string is always fully qualified and may carry the leading `\`: `class_exists('\A\P')`.

try { throw new \Exception("x"); } catch (\Exception $e) { echo $e->getMessage(); }   // => x

# $var "…$var…"

"text $var text"   //  double-quoted interpolation

Double-quoted strings and heredoc-free literals interpolate a bare `$name`. DIVERGENCE: the braced form `{$expr}` is NOT interpolated — the braces are emitted literally around the substituted variable — and heredoc/nowdoc (`<<<EOT`) is not lexed at all.

$s = "ab"; echo "v=$s";   // => v=ab
echo "{$s}";      // => {ab}   (PHP 8 prints: ab)

Cast

# (void)

(void) expr;

PHP 8.5 discard cast: evaluates the expression and explicitly ignores its value. It is a statement-level form — `echo (void) 1;`, `$x = (void) f();` and `return (void) 1;` are syntax errors naming the token `(void)`.

(void) print("a");   // => a

# (int)

(int) expr   //  also (integer)

Casts to integer by desugaring to a call to `intval`, which takes the leading numeric prefix of a string and yields `0` when there is none.

echo (int) "42px";   // => 42

# (float)

(float) expr   //  also (double), (real)

Casts to float by desugaring to `floatval`. All three spellings map to the same call.

echo (float) "3.5kg";   // => 3.5

# (string)

(string) expr

Casts to string by desugaring to `strval`. An object calls its `__toString`; one without it throws `Error` (message: `Object of class X could not be converted to string`).

echo (string) 123;   // => 123

# (bool)

(bool) expr   //  also (boolean)

Casts to boolean by desugaring to `boolval`. Falsey values are `0`, `0.0`, `""`, `"0"`, the empty array, and null.

var_dump((bool) 0, (bool) "0", (bool) "a");   // => bool(false) bool(false) bool(true)

# (array) (object) (unset)

(array) expr   //  NOT SUPPORTED

Listed for completeness: `cast_fn` in `src/parser.rs` maps only int, float, string, and bool. `(array)`, `(object)`, and `(unset)` are not recognized as casts, so `(array) $x` parses as a constant fetch of the bareword `array` followed by `$x` and is a syntax error.

Magic method

# __construct

public function __construct(mixed ...$args)

The constructor, invoked automatically by `new`. A parameter carrying a visibility or `readonly` keyword is promoted to a property of the same name and assigned before the body runs.

class P { function __construct(public $x) {} } echo (new P(4))->x;   // => 4

# __destruct

public function __destruct(): void

The destructor. Run at request end, after the shutdown functions: first for the globals that alone hold an object, newest first (and for whatever only that object held), then for every other live object in creation order. DIVERGENCE: an object released mid-script (`unset`, reassignment, a local going out of scope) is destroyed at request end, not at the release — phplang keeps no reference counts. Skipped after a fatal error that is not an uncaught exception.

class D { function __destruct() { echo "bye"; } } $d = new D; echo "end ";   // => end bye

# __invoke

public function __invoke(mixed ...$args): mixed

Called when a value is used as a function. Declaring it makes every instance of the class callable — `$obj(…)`, `is_callable($obj)`, and passing `$obj` where a callback is expected (`array_map`, `usort`, `Closure::fromCallable`) all resolve through it.

class Twice { public function __invoke($x) { return $x * 2; } }
echo (new Twice)(21);   // => 42

# __toString

public function __toString(): string

Declared by the prelude `Exception` and `Error` classes and callable like any other method. Invoked implicitly by `echo`, `(string)`, `.` and interpolation; an object without it throws `Error` on conversion.

class C { function __toString() { return "S"; } }
$o = new C; echo $o->__toString(), "|", $o;   // => S|S

# __get

public function __get(string $name): mixed

Called when a property is read that the object does not carry — because no class declared it, because it was `unset`, or because its visibility puts it out of reach of the reading scope. Consulted BEFORE any access error, so a class with `__get` never reports `Cannot access private property`. While it runs for a given property it is not re-entered for that same property, so `__get($n) { return $this->$n; }` terminates rather than recursing.

class C { function __get($n) { return "g:$n"; } } echo (new C)->zz;   // => g:zz

# __set

public function __set(string $name, mixed $value): void

Called when a property is WRITTEN that the object does not carry or cannot reach. A write it handles creates no real property, so `get_object_vars` stays empty. In a read-modify-write (`$o->p .= "x"`, `$o->p++`) it is used only when the class ALSO defines `__get`: `__set` is half of a pair, and without `__get` supplying the old value the reference reads and writes the property directly instead.

class C { function __set($n, $v) { echo "set:$n"; } } $o = new C; $o->zz = 1;   // => set:zz

# __isset

public function __isset(string $name): bool

Called by `isset()` and `empty()` on a property the object does not carry or cannot reach. It answers the question by itself for `isset()`; for `empty()` and `??` a true answer is then followed by `__get` to obtain the value.

class C { function __isset($n) { return $n === "ok"; } }
$o = new C; var_dump(isset($o->ok), isset($o->no));   // => bool(true) bool(false)

# __unset

public function __unset(string $name): void

Called by `unset()` on a property the object does not carry or cannot reach. Like the others it is consulted before any access error, so a class defining it can be asked to unset a private property from outside without a fatal.

class C { function __unset($n) { echo "unset:$n"; } }
$o = new C; unset($o->zz);   // => unset:zz

# __rust_compile

__rust_compile(string $base64Body, int $line): void

The internal builtin a `rust { … }` block desugars to. It compiles and loads the encoded Rust body and registers each exported `pub extern "C"` function under its bare name. Programs call it only through the `rust` construct, never directly.

Predefined constant

# PHP_INT_MAX

PHP_INT_MAX: int = 9223372036854775807

The largest representable integer. phplang integers are 64-bit signed, so this is `i64::MAX`.

echo PHP_INT_MAX;   // => 9223372036854775807

# PHP_INT_MIN

PHP_INT_MIN: int = -9223372036854775808

The smallest representable integer, `i64::MIN`.

# PHP_INT_SIZE

PHP_INT_SIZE: int = 8

Integer width in bytes. Always 8 — phplang has no 32-bit build.

# PHP_FLOAT_DIG

PHP_FLOAT_DIG: int = 15

Number of decimal digits a float can round-trip.

# PHP_FLOAT_EPSILON

PHP_FLOAT_EPSILON: float = 2.220446049250313E-16

The smallest positive value that, added to 1.0, produces a different float (`f64::EPSILON`).

# PHP_FLOAT_MAX

PHP_FLOAT_MAX: float = 1.7976931348623157E+308

The largest finite float, `f64::MAX`.

# PHP_FLOAT_MIN

PHP_FLOAT_MIN: float = 2.2250738585072014E-308

The smallest positive normalized float, `f64::MIN_POSITIVE`.

# INF

INF: float = f64::INFINITY

Positive floating-point infinity. `is_infinite(INF)` is true.

# NAN

NAN: float = f64::NAN

The floating-point not-a-number value. It compares unequal to everything, including itself.

# PHP_VERSION

PHP_VERSION: string

The version of the reference PHP this engine is measured against (`major.minor.release`); `PHP_MAJOR_VERSION`, `PHP_MINOR_VERSION`, `PHP_RELEASE_VERSION`, `PHP_VERSION_ID` and `phpversion()` derive from it.

var_dump(version_compare(PHP_VERSION, "8.4", ">="));   // => bool(true)

# PHP_EXTRA_VERSION

PHP_EXTRA_VERSION: string = ""

The version's suffix; empty for a release build.

# PHP_SAPI

PHP_SAPI: string = "cli"

The server API the engine runs under — always the command-line SAPI, the same answer as `php_sapi_name()`.

# PHP_BINARY

PHP_BINARY: string

The interpreter's own path, as `php_binary_init` computes it: the `realpath` of `argv[0]`, or — for a bare name with no `/` — of the first executable regular file of that name along `PATH`. The empty string when neither resolves.

echo PHP_BINARY === realpath(PHP_BINARY) ? "resolved" : "";   // => resolved

# PHP_DEBUG

PHP_DEBUG: bool = false

Whether this is a debug build.

# PHP_ZTS

PHP_ZTS: bool = false

Whether this is a thread-safe build.

# ZEND_THREAD_SAFE

ZEND_THREAD_SAFE: bool = false

Whether the engine is thread-safe.

# ZEND_DEBUG_BUILD

ZEND_DEBUG_BUILD: bool = false

Whether the engine is a debug build.

# PHP_MAXPATHLEN

PHP_MAXPATHLEN: int = 1024

The longest file path the build supports.

# PHP_FD_SETSIZE

PHP_FD_SETSIZE: int = 1024

The highest file descriptor `select` can watch.

# PHP_SHLIB_SUFFIX

PHP_SHLIB_SUFFIX: string = "so"

The file suffix of a loadable extension.

# M_LNPI

M_LNPI: float = 1.1447298858494002

`log(M_PI)`.

# INI_USER

INI_USER: int = 1

An ini setting changeable from a script.

# INI_PERDIR

INI_PERDIR: int = 2

An ini setting changeable per directory.

# INI_SYSTEM

INI_SYSTEM: int = 4

An ini setting changeable only in php.ini.

# INI_ALL

INI_ALL: int = 7

An ini setting changeable anywhere.

# CONNECTION_ABORTED

CONNECTION_ABORTED: int = 1

`connection_status()` bit: the client disconnected.

# CONNECTION_NORMAL

CONNECTION_NORMAL: int = 0

`connection_status()`: the connection is up.

# CONNECTION_TIMEOUT

CONNECTION_TIMEOUT: int = 2

`connection_status()` bit: the time limit was reached.

# PHP_QUERY_RFC1738

PHP_QUERY_RFC1738: int = 1

`http_build_query` encoding: spaces as `+`.

# PHP_QUERY_RFC3986

PHP_QUERY_RFC3986: int = 2

`http_build_query` encoding: spaces as `%20`.

# UPLOAD_ERR_OK

UPLOAD_ERR_OK: int = 0

File upload status: no error.

# UPLOAD_ERR_INI_SIZE

UPLOAD_ERR_INI_SIZE: int = 1

File upload status: larger than `upload_max_filesize`.

# UPLOAD_ERR_FORM_SIZE

UPLOAD_ERR_FORM_SIZE: int = 2

File upload status: larger than the form's `MAX_FILE_SIZE`.

# UPLOAD_ERR_PARTIAL

UPLOAD_ERR_PARTIAL: int = 3

File upload status: only partly received.

# UPLOAD_ERR_NO_FILE

UPLOAD_ERR_NO_FILE: int = 4

File upload status: no file was sent.

# UPLOAD_ERR_NO_TMP_DIR

UPLOAD_ERR_NO_TMP_DIR: int = 6

File upload status: no temporary directory.

# UPLOAD_ERR_CANT_WRITE

UPLOAD_ERR_CANT_WRITE: int = 7

File upload status: the file could not be written.

# UPLOAD_ERR_EXTENSION

UPLOAD_ERR_EXTENSION: int = 8

File upload status: an extension stopped the upload.

# PHP_MAJOR_VERSION

PHP_MAJOR_VERSION: int = 8

Major component of `PHP_VERSION`.

# PHP_MINOR_VERSION

PHP_MINOR_VERSION: int

Minor component of `PHP_VERSION`.

# PHP_RELEASE_VERSION

PHP_RELEASE_VERSION: int

Release component of `PHP_VERSION`.

# PHP_VERSION_ID

PHP_VERSION_ID: int

The version as a single comparable integer, `major*10000 + minor*100 + release`.

# PHP_OS

PHP_OS: string = "Darwin" | "WINNT" | "Linux"

The host operating system, resolved at COMPILE time from `cfg!(target_os)` rather than by a runtime `uname(2)`.

# PHP_OS_FAMILY

PHP_OS_FAMILY: string = "Windows" | "Darwin" | "Linux"

The operating-system family, also decided at compile time. Every non-Windows, non-macOS target reports `Linux`.

# PHP_EOL

PHP_EOL: string = "\n"

The platform line terminator. DIVERGENCE: it is `\n` unconditionally, including on Windows builds where PHP uses `\r\n`.

echo "a" . PHP_EOL . "b";   // => a<newline>b

# STDIN

STDIN: resource

Resource 1, the process's standard input. Reads pull from it lazily — a line at a time for `fgets`/`fscanf` — so a prompt-and-read script works interactively.

$line = fgets(STDIN);

# STDOUT

STDOUT: resource

Resource 2, the process's standard output. A write bypasses output buffering, as in PHP.

fwrite(STDOUT, "hi\n");   // => hi

# STDERR

STDERR: resource

Resource 3, the process's standard error.

fwrite(STDERR, "oops\n");

# DIRECTORY_SEPARATOR

DIRECTORY_SEPARATOR: string = "/" | "\\"

The path component separator, `\` on Windows builds and `/` everywhere else.

# PATH_SEPARATOR

PATH_SEPARATOR: string = ":" | ";"

The separator between entries in a path list, `;` on Windows builds and `:` everywhere else.

# PHP_ROUND_HALF_UP

PHP_ROUND_HALF_UP: int = 1

Rounding mode: halves away from zero. This is the behaviour `round()` always uses — the mode argument is not read.

# PHP_ROUND_HALF_DOWN

PHP_ROUND_HALF_DOWN: int = 2

Rounding mode: halves toward zero. Defined for source compatibility; `round()` ignores the mode argument.

# PHP_ROUND_HALF_EVEN

PHP_ROUND_HALF_EVEN: int = 3

Rounding mode: halves to the nearest even value. Honoured: `round(2.5, 0, PHP_ROUND_HALF_EVEN)` is `2` and `round(3.5, 0, PHP_ROUND_HALF_EVEN)` is `4`.

# PHP_ROUND_HALF_ODD

PHP_ROUND_HALF_ODD: int = 4

Rounding mode: halves to the nearest odd value. Honoured: `round(2.5, 0, PHP_ROUND_HALF_ODD)` is `3` and `round(3.5, 0, PHP_ROUND_HALF_ODD)` is `3`.

# E_ERROR

E_ERROR: int = 1

Error level for a fatal runtime error. phplang has no error-level machinery, so this is a value for scripts to pass around.

# E_WARNING

E_WARNING: int = 2

Error level for a non-fatal runtime warning.

# E_PARSE

E_PARSE: int = 4

Error level for a compile-time parse error.

# E_NOTICE

E_NOTICE: int = 8

Error level for a runtime notice.

# E_STRICT

E_STRICT: int = 2048

Error level for interoperability suggestions. The level was REMOVED in PHP 8.4 — nothing raises it and it is not part of `E_ALL` — but the constant remains so an existing `E_ALL & ~E_STRICT` still parses. Every use of it raises `Deprecated: Constant E_STRICT is deprecated since 8.4, the error level was removed`.

# E_DEPRECATED

E_DEPRECATED: int = 8192

Error level for a deprecation notice.

# E_ALL

E_ALL: int = 30719

Every error level that still exists. It is 30719, not the pre-8.4 32767: PHP 8.4 removed `E_STRICT` and took its bit out of `E_ALL`, so `E_ALL & E_STRICT` is 0. This is also the level a program starts at unless `-d error_reporting=…` says otherwise.

echo E_ALL, "|", E_ALL & E_STRICT;   // => 30719|0

# E_USER_ERROR

E_USER_ERROR: int = 256

User-generated error level. Passed to `trigger_error()`, it prints `Fatal error: …` to stderr but does NOT halt the program.

# E_USER_WARNING

E_USER_WARNING: int = 512

User-generated warning level; `trigger_error()` labels it `Warning`.

# E_USER_NOTICE

E_USER_NOTICE: int = 1024

User-generated notice level and the default for `trigger_error()`, which labels it `Notice`.

# E_USER_DEPRECATED

E_USER_DEPRECATED: int = 16384

User-generated deprecation level; `trigger_error()` labels it `Deprecated`.

# SORT_REGULAR

SORT_REGULAR: int = 0

Sort flag for comparing items normally. phplang's sorts always compare this way — the flag argument is not read.

# SORT_NUMERIC

SORT_NUMERIC: int = 1

Sort flag for numeric comparison. Accepted by `array_multisort` as a column type marker; the plain sorts ignore it.

# PHP_OUTPUT_HANDLER_START

PHP_OUTPUT_HANDLER_START: int = 1

Handler phase bit: set on the first call a handler receives.

# PHP_OUTPUT_HANDLER_WRITE

PHP_OUTPUT_HANDLER_WRITE: int = 0

Handler phase value of an ordinary write that filled a chunk.

# PHP_OUTPUT_HANDLER_FLUSH

PHP_OUTPUT_HANDLER_FLUSH: int = 4

Handler phase bit: the buffer is being flushed (`ob_flush`).

# PHP_OUTPUT_HANDLER_CLEAN

PHP_OUTPUT_HANDLER_CLEAN: int = 2

Handler phase bit: the buffer is being cleaned (`ob_clean`, `ob_end_clean`, `ob_get_clean`).

# PHP_OUTPUT_HANDLER_FINAL

PHP_OUTPUT_HANDLER_FINAL: int = 8

Handler phase bit: the last call, as the buffer is removed.

# PHP_OUTPUT_HANDLER_CONT

PHP_OUTPUT_HANDLER_CONT: int = 0

Alias of `PHP_OUTPUT_HANDLER_WRITE`.

# PHP_OUTPUT_HANDLER_END

PHP_OUTPUT_HANDLER_END: int = 8

Alias of `PHP_OUTPUT_HANDLER_FINAL`.

# PHP_OUTPUT_HANDLER_CLEANABLE

PHP_OUTPUT_HANDLER_CLEANABLE: int = 16

`ob_start` flag: the buffer may be cleaned.

# PHP_OUTPUT_HANDLER_FLUSHABLE

PHP_OUTPUT_HANDLER_FLUSHABLE: int = 32

`ob_start` flag: the buffer may be flushed.

# PHP_OUTPUT_HANDLER_REMOVABLE

PHP_OUTPUT_HANDLER_REMOVABLE: int = 64

`ob_start` flag: the buffer may be removed before the end of the script.

# PHP_OUTPUT_HANDLER_STDFLAGS

PHP_OUTPUT_HANDLER_STDFLAGS: int = 112

The default `ob_start` flags: cleanable, flushable and removable.

# PHP_OUTPUT_HANDLER_STARTED

PHP_OUTPUT_HANDLER_STARTED: int = 4096

`ob_get_status` flag: the handler has run.

# PHP_OUTPUT_HANDLER_DISABLED

PHP_OUTPUT_HANDLER_DISABLED: int = 8192

`ob_get_status` flag: the handler returned false and now passes output through.

# PHP_OUTPUT_HANDLER_PROCESSED

PHP_OUTPUT_HANDLER_PROCESSED: int = 16384

`ob_get_status` flag: the handler has processed its buffer.

# SORT_STRING

SORT_STRING: int = 2

Sort flag for string comparison, with the same limited effect as `SORT_NUMERIC`.

# SORT_DESC

SORT_DESC: int = 3

Descending sort order for `array_multisort` columns.

# SORT_ASC

SORT_ASC: int = 4

Ascending sort order for `array_multisort` columns, and its default.

# SORT_LOCALE_STRING

SORT_LOCALE_STRING: int = 5

Locale-aware string sort flag. Defined for compatibility; phplang has no locale support.

# SORT_NATURAL

SORT_NATURAL: int = 6

Natural-order sort flag. Use `natsort()` for the real behaviour — the plain sorts do not read the flag.

# SORT_FLAG_CASE

SORT_FLAG_CASE: int = 8

Bit combined with `SORT_STRING` or `SORT_NATURAL` to fold case. Honoured: `sort($a, SORT_STRING|SORT_FLAG_CASE)` orders `["B", "a"]` as `["a", "B"]`.

# COUNT_NORMAL

COUNT_NORMAL: int = 0

`count()` mode counting only top-level elements. This is the only mode implemented.

# COUNT_RECURSIVE

COUNT_RECURSIVE: int = 1

`count()` mode that counts nested elements too: a nested array counts as one element AND contributes its own contents, at every depth. Recursion is into arrays only — a nested `Countable` is a single element and its own `count()` is not consulted.

echo count([1, [2, 3]], COUNT_RECURSIVE);   // => 4

# STR_PAD_RIGHT

STR_PAD_RIGHT: int = 1

`str_pad()` / `mb_str_pad()` mode padding on the right. The default, and the fallback for an unrecognized mode.

# STR_PAD_LEFT

STR_PAD_LEFT: int = 0

`str_pad()` / `mb_str_pad()` mode padding on the left.

echo str_pad("5", 3, "0", STR_PAD_LEFT);   // => 005

# STR_PAD_BOTH

STR_PAD_BOTH: int = 2

`str_pad()` / `mb_str_pad()` mode padding on both sides, with the left side floored.

# ARRAY_FILTER_USE_KEY

ARRAY_FILTER_USE_KEY: int = 2

`array_filter()` mode passing only the key to the callback.

# ARRAY_FILTER_USE_BOTH

ARRAY_FILTER_USE_BOTH: int = 1

`array_filter()` mode passing the value and then the key to the callback.

# PREG_PATTERN_ORDER

PREG_PATTERN_ORDER: int = 1

`preg_match_all()` ordering that groups results by capture group: `$matches[group][set]`. The default.

# PREG_SET_ORDER

PREG_SET_ORDER: int = 2

`preg_match_all()` ordering that groups results by match: `$matches[set][group]`. This bit is honoured.

# PREG_OFFSET_CAPTURE

PREG_OFFSET_CAPTURE: int = 256

Turns every `$matches` cell into a `[text, offset]` pair. The offset is a BYTE position, which is what PHP reports even under `/u`, where the subject is walked as UTF-8 but positions are still counted in bytes. A group that did not participate is `['', -1]`, not `['', 0]`. Honoured by `preg_match`, `preg_match_all` and `preg_replace_callback`; `preg_split` has its own separate `PREG_SPLIT_OFFSET_CAPTURE` bit.

# PREG_UNMATCHED_AS_NULL

PREG_UNMATCHED_AS_NULL: int = 512

Reports a non-participating group as null rather than an empty string, and SUPPRESSES the trailing-unmatched trim so the row keeps its full width. Combined with `PREG_OFFSET_CAPTURE` such a cell is `[null, -1]`.

# PREG_SPLIT_NO_EMPTY

PREG_SPLIT_NO_EMPTY: int = 1

`preg_split()` flag dropping empty pieces from the result. Honoured.

# PREG_SPLIT_DELIM_CAPTURE

PREG_SPLIT_DELIM_CAPTURE: int = 2

`preg_split()` flag interleaving captured delimiter groups into the result. Honoured.

# PREG_SPLIT_OFFSET_CAPTURE

PREG_SPLIT_OFFSET_CAPTURE: int = 4

`preg_split()` flag emitting `[piece, byteOffset]` pairs instead of bare strings. Honoured.

# JSON_HEX_TAG

JSON_HEX_TAG: int = 1

`json_encode()` flag escaping `<` and `>` as `\u003C` and `\u003E`. The hex digits are UPPER case, where the control and unicode escapes spell theirs in lower.

# JSON_HEX_AMP

JSON_HEX_AMP: int = 2

`json_encode()` flag escaping `&` as `\u0026`.

# JSON_HEX_APOS

JSON_HEX_APOS: int = 4

`json_encode()` flag escaping `'` as `\u0027`.

# JSON_HEX_QUOT

JSON_HEX_QUOT: int = 8

`json_encode()` flag escaping `"` as `\u0022` instead of `\"`.

# JSON_FORCE_OBJECT

JSON_FORCE_OBJECT: int = 16

`json_encode()` flag emitting a JSON object even for an array whose keys are already `0..n`.

# JSON_NUMERIC_CHECK

JSON_NUMERIC_CHECK: int = 32

`json_encode()` flag encoding a numeric string as the number it reads as, by PHP's own `is_numeric_string` — so `" 5"` and `"5 "` convert while `"0x1A"` does not. An integral result loses its fractional part (`"1e3"` encodes as `1000`), and a string that reads as a non-finite double (`"1e999"`) stays a string. Array KEYS are unaffected; JSON has no non-string key.

# JSON_UNESCAPED_SLASHES

JSON_UNESCAPED_SLASHES: int = 64

`json_encode()` flag leaving `/` unescaped, where the default writes `\/`.

# JSON_PRETTY_PRINT

JSON_PRETTY_PRINT: int = 128

`json_encode()` flag requesting indented output: four spaces per level, and `": "` rather than `":"` after a key.

echo json_encode(["a" => 1], JSON_PRETTY_PRINT);   // => {
    "a": 1
}

# JSON_UNESCAPED_UNICODE

JSON_UNESCAPED_UNICODE: int = 256

`json_encode()` flag emitting literal UTF-8 instead of `\uXXXX`.

# JSON_PARTIAL_OUTPUT_ON_ERROR

JSON_PARTIAL_OUTPUT_ON_ERROR: int = 512

`json_encode()` flag substituting for a value that cannot be encoded instead of failing: a cycle and a resource become `null`, a non-finite float and a pure enum case become `0`. The encode never fails or throws under it, `JSON_THROW_ON_ERROR` included, and `json_last_error()` reports the LAST error substituted, in document order.

echo json_encode([1, NAN], JSON_PARTIAL_OUTPUT_ON_ERROR);   // => [1,0]

# JSON_PRESERVE_ZERO_FRACTION

JSON_PRESERVE_ZERO_FRACTION: int = 1024

`json_encode()` flag appending `.0` to an integral float — and to a numeric string `JSON_NUMERIC_CHECK` converts to one — so it decodes back as a float. A spelling that already has a fraction or exponent (`1.0e+25`) is left alone.

echo json_encode([1.0], JSON_PRESERVE_ZERO_FRACTION);   // => [1.0]

# JSON_UNESCAPED_LINE_TERMINATORS

JSON_UNESCAPED_LINE_TERMINATORS: int = 2048

`json_encode()` flag leaving U+2028 and U+2029 raw under `JSON_UNESCAPED_UNICODE`. Without it those two stay `\u2028`/`\u2029` even when every other character is written literally, because they end a line in JavaScript.

# JSON_THROW_ON_ERROR

JSON_THROW_ON_ERROR: int = 4194304

Flag asking the JSON functions to throw `JsonException` instead of returning `false`/null. Honoured by `json_encode`, `json_decode` and `json_validate`: the exception's `getCode()` is the `JSON_ERROR_*` constant, and `json_last_error()` is left at `JSON_ERROR_NONE` because the failure travelled on the throw instead of being recorded for a later read.

# JSON_OBJECT_AS_ARRAY

JSON_OBJECT_AS_ARRAY: int = 1

`json_decode()` flag decoding JSON objects as PHP arrays. Consulted only when `$associative` is left null, which is `ext/json`'s own precedence — an explicit `$associative` wins over the flag in both directions.

# JSON_BIGINT_AS_STRING

JSON_BIGINT_AS_STRING: int = 2

`json_decode()` flag keeping an integer literal too large for `int` as the string of its digits, sign included, instead of the nearest float. A float literal is unaffected, even one that overflows to `INF`.

var_dump(json_decode("[12345678901234567890]", true, 512, JSON_BIGINT_AS_STRING)[0]);   // => string(20) "12345678901234567890"

# JSON_ERROR_NONE

JSON_ERROR_NONE: int = 0

`json_last_error()` code meaning the last decode succeeded.

# JSON_ERROR_DEPTH

JSON_ERROR_DEPTH: int = 1

`json_last_error()` code meaning the maximum nesting depth was exceeded.

# JSON_ERROR_STATE_MISMATCH

JSON_ERROR_STATE_MISMATCH: int = 2

`json_last_error()` code for invalid or malformed JSON.

# JSON_ERROR_CTRL_CHAR

JSON_ERROR_CTRL_CHAR: int = 3

`json_last_error()` code for a raw control character inside a string.

# JSON_ERROR_SYNTAX

JSON_ERROR_SYNTAX: int = 4

`json_last_error()` code for a syntax error.

# JSON_ERROR_UTF8

JSON_ERROR_UTF8: int = 5

`json_last_error()` code for malformed UTF-8.

# JSON_ERROR_RECURSION

JSON_ERROR_RECURSION: int = 6

`json_last_error()` code set by `json_encode()` for an array or object that contains itself.

# JSON_ERROR_INF_OR_NAN

JSON_ERROR_INF_OR_NAN: int = 7

`json_last_error()` code set by `json_encode()` for a `NAN` or `INF` float, which JSON cannot spell.

# JSON_ERROR_UNSUPPORTED_TYPE

JSON_ERROR_UNSUPPORTED_TYPE: int = 8

`json_last_error()` code set by `json_encode()` for a value of a type JSON cannot spell: a stream resource, open or closed. `JSON_PARTIAL_OUTPUT_ON_ERROR` writes `null` in its place.

# JSON_ERROR_INVALID_PROPERTY_NAME

JSON_ERROR_INVALID_PROPERTY_NAME: int = 9

`json_last_error()` code set by `json_decode()` for an object key starting with a NUL byte when the object decodes to a `stdClass` (a NUL-led name is how PHP spells a mangled non-public property). Decoding to an array accepts the key, and `json_validate()` never reports it.

# JSON_ERROR_UTF16

JSON_ERROR_UTF16: int = 10

`json_last_error()` code for a lone UTF-16 surrogate in a `\u` escape.

# JSON_ERROR_NON_BACKED_ENUM

JSON_ERROR_NON_BACKED_ENUM: int = 11

`json_last_error()` code set by `json_encode()` for a case of a pure (non-backed) enum, which has no value to encode.

# PHP_URL_SCHEME

PHP_URL_SCHEME: int = 0

`parse_url()`'s `$component` selector for the scheme (`https`). A component the URL does not carry reads back as null.

# PHP_URL_HOST

PHP_URL_HOST: int = 1

`parse_url()`'s `$component` selector for the host. A component the URL does not carry reads back as null.

# PHP_URL_PORT

PHP_URL_PORT: int = 2

`parse_url()`'s `$component` selector for the port, as an int. A component the URL does not carry reads back as null.

# PHP_URL_USER

PHP_URL_USER: int = 3

`parse_url()`'s `$component` selector for the userinfo user. A component the URL does not carry reads back as null.

# PHP_URL_PASS

PHP_URL_PASS: int = 4

`parse_url()`'s `$component` selector for the userinfo password. A component the URL does not carry reads back as null.

# PHP_URL_PATH

PHP_URL_PATH: int = 5

`parse_url()`'s `$component` selector for the path. A component the URL does not carry reads back as null.

# PHP_URL_QUERY

PHP_URL_QUERY: int = 6

`parse_url()`'s `$component` selector for the query string, without the `?`. A component the URL does not carry reads back as null.

# PHP_URL_FRAGMENT

PHP_URL_FRAGMENT: int = 7

`parse_url()`'s `$component` selector for the fragment, without the `#`. A component the URL does not carry reads back as null.

# INPUT_GET

INPUT_GET: int = 1

`filter_has_var()` input source for query parameters. phplang is standalone with no request context, so the lookup always reports false.

# INPUT_POST

INPUT_POST: int = 0

`filter_has_var()` input source for form-body parameters, with the same always-false result.

# FILTER_DEFAULT

FILTER_DEFAULT: int = 516

`filter_var()` filter that returns the value string-cast without validating. Also the fallback for any unrecognized filter id.

# FILTER_UNSAFE_RAW

FILTER_UNSAFE_RAW: int = 516

The same id as `FILTER_DEFAULT` — an unfiltered string-cast pass-through.

# FILTER_VALIDATE_INT

FILTER_VALIDATE_INT: int = 257

Validates an integer, honouring `min_range`/`max_range` options and the hex/octal flags. Leading zeros are rejected.

var_dump(filter_var("42", FILTER_VALIDATE_INT));   // => int(42)

# FILTER_VALIDATE_BOOLEAN

FILTER_VALIDATE_BOOLEAN: int = 258

Validates a boolean: `1/true/on/yes` are true, `0/false/off/no/""` are false, anything else fails.

# FILTER_VALIDATE_BOOL

FILTER_VALIDATE_BOOL: int = 258

The PHP 8 spelling of `FILTER_VALIDATE_BOOLEAN`, sharing its id and behaviour.

# FILTER_VALIDATE_FLOAT

FILTER_VALIDATE_FLOAT: int = 259

Validates a float. Every byte must be in `[0-9+-.eE]`, so `inf` and `nan` fail, and a non-finite result is rejected.

# FILTER_VALIDATE_REGEXP

FILTER_VALIDATE_REGEXP: int = 272

Validates against the `options['regexp']` pattern, compiled by the same engine pair `preg_match` uses — so the delimiter rules, the modifier set, look-around and backreferences all behave identically, and a pattern fault raises `Warning: filter_var(): <reason>` and sets `preg_last_error()` exactly as the reference does.

# FILTER_VALIDATE_DOMAIN

FILTER_VALIDATE_DOMAIN: int = 277

Validates a 1-253 byte domain, adding an RFC 1123 label check only when `FILTER_FLAG_HOSTNAME` is set.

# FILTER_VALIDATE_URL

FILTER_VALIDATE_URL: int = 273

Validates a URL, requiring both a scheme and a host.

# FILTER_VALIDATE_EMAIL

FILTER_VALIDATE_EMAIL: int = 274

Validates an email address of at most 320 bytes against a dotted-domain pattern.

var_dump(filter_var("a@b.co", FILTER_VALIDATE_EMAIL));   // => string(6) "a@b.co"

# FILTER_VALIDATE_IP

FILTER_VALIDATE_IP: int = 275

Validates an IP address with `std::net`, gated by the IPv4/IPv6 flags. The private- and reserved-range flags are not implemented.

# FILTER_VALIDATE_MAC

FILTER_VALIDATE_MAC: int = 276

Validates a MAC address in the 17-character `:`/`-` form or the 14-character `xxxx.xxxx.xxxx` form.

# FILTER_SANITIZE_STRING

FILTER_SANITIZE_STRING: int = 513

Strips `<…>` tags then encodes `"` and `'` as numeric entities. Sanitizers never fail. Deprecated since 8.1: every use of the constant raises `Deprecated: Constant FILTER_SANITIZE_STRING is deprecated since 8.1, use htmlspecialchars() instead`.

# FILTER_SANITIZE_STRIPPED

FILTER_SANITIZE_STRIPPED: int = 513

The legacy alias of `FILTER_SANITIZE_STRING`, sharing its id, and deprecated the same way.

# FILTER_SANITIZE_ENCODED

FILTER_SANITIZE_ENCODED: int = 514

URL-encoding sanitizer id. DIVERGENCE: not implemented — it falls through to the `FILTER_DEFAULT` pass-through.

# FILTER_SANITIZE_SPECIAL_CHARS

FILTER_SANITIZE_SPECIAL_CHARS: int = 515

Encodes `&`, `<`, `>`, `"`, and `'` as numeric character references.

# FILTER_SANITIZE_FULL_SPECIAL_CHARS

FILTER_SANITIZE_FULL_SPECIAL_CHARS: int = 522

Encodes the same five characters as named entities: `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#039;`.

# FILTER_SANITIZE_EMAIL

FILTER_SANITIZE_EMAIL: int = 517

Keeps only characters legal in an email address, dropping everything else.

# FILTER_SANITIZE_URL

FILTER_SANITIZE_URL: int = 518

Keeps only characters legal in a URL.

# FILTER_SANITIZE_NUMBER_INT

FILTER_SANITIZE_NUMBER_INT: int = 519

Keeps only digits and the `+`/`-` signs.

# FILTER_SANITIZE_NUMBER_FLOAT

FILTER_SANITIZE_NUMBER_FLOAT: int = 520

Keeps digits and signs, plus `.`, `,`, and `e`/`E` when the matching ALLOW flag is set.

# FILTER_SANITIZE_ADD_SLASHES

FILTER_SANITIZE_ADD_SLASHES: int = 523

Backslash-escaping sanitizer id. DIVERGENCE: not implemented — it falls through to the `FILTER_DEFAULT` pass-through.

# FILTER_FLAG_ALLOW_OCTAL

FILTER_FLAG_ALLOW_OCTAL: int = 1

Lets `FILTER_VALIDATE_INT` accept an unsigned `0`-prefixed octal literal.

# FILTER_FLAG_ALLOW_HEX

FILTER_FLAG_ALLOW_HEX: int = 2

Lets `FILTER_VALIDATE_INT` accept an unsigned `0x`-prefixed hex literal.

# FILTER_FLAG_STRIP_LOW

FILTER_FLAG_STRIP_LOW: int = 4

Flag asking sanitizers to drop bytes below 0x20. DIVERGENCE: not implemented.

# FILTER_FLAG_STRIP_HIGH

FILTER_FLAG_STRIP_HIGH: int = 8

Flag asking sanitizers to drop bytes at or above 0x80. DIVERGENCE: not implemented.

# FILTER_FLAG_ALLOW_FRACTION

FILTER_FLAG_ALLOW_FRACTION: int = 4096

Lets `FILTER_SANITIZE_NUMBER_FLOAT` keep `.`.

# FILTER_FLAG_ALLOW_THOUSAND

FILTER_FLAG_ALLOW_THOUSAND: int = 8192

Lets `FILTER_SANITIZE_NUMBER_FLOAT` keep `,`, and lets `FILTER_VALIDATE_FLOAT` strip it before parsing.

# FILTER_FLAG_ALLOW_SCIENTIFIC

FILTER_FLAG_ALLOW_SCIENTIFIC: int = 16384

Lets `FILTER_SANITIZE_NUMBER_FLOAT` keep `e` and `E`.

# FILTER_FLAG_IPV4

FILTER_FLAG_IPV4: int = 1048576

Restricts `FILTER_VALIDATE_IP` to IPv4. It shares its integer with `FILTER_FLAG_HOSTNAME`, so passing it to `FILTER_VALIDATE_DOMAIN` silently enables the hostname check.

# FILTER_FLAG_IPV6

FILTER_FLAG_IPV6: int = 2097152

Restricts `FILTER_VALIDATE_IP` to IPv6. Setting neither family flag, or both, accepts either.

# FILTER_FLAG_HOSTNAME

FILTER_FLAG_HOSTNAME: int = 1048576

Adds an RFC 1123 label check to `FILTER_VALIDATE_DOMAIN`. Shares its integer with `FILTER_FLAG_IPV4`.

# FILTER_NULL_ON_FAILURE

FILTER_NULL_ON_FAILURE: int = 134217728

Makes a failing `filter_var()` return null instead of false. Honoured by every validating filter.

# FILTER_REQUIRE_SCALAR

FILTER_REQUIRE_SCALAR: int = 33554432

Flag requiring a scalar subject. Redundant here: an array subject already fails every filter.

# FILTER_REQUIRE_ARRAY

FILTER_REQUIRE_ARRAY: int = 16777216

Flag requiring an array subject. DIVERGENCE: not implemented.

# FILTER_FORCE_ARRAY

FILTER_FORCE_ARRAY: int = 67108864

Flag wrapping a scalar result in an array. DIVERGENCE: not implemented.

# ICONV_IMPL

ICONV_IMPL: string = "libiconv"

The iconv implementation the reference build links, whose `//TRANSLIT` table `iconv()` reproduces.

# ICONV_VERSION

ICONV_VERSION: string = "1.11"

The version of that implementation.

# MB_CASE_UPPER

MB_CASE_UPPER: int = 0

`mb_convert_case()` mode uppercasing the whole string. Also the fallback for any unrecognized mode.

# MB_CASE_LOWER

MB_CASE_LOWER: int = 1

`mb_convert_case()` mode lowercasing the whole string.

# MB_CASE_TITLE

MB_CASE_TITLE: int = 2

`mb_convert_case()` mode title-casing each run of letters. PHP's `_SIMPLE` variants (3-5) are not distinguished and fall into the uppercase branch.

# FILE_USE_INCLUDE_PATH

FILE_USE_INCLUDE_PATH: int = 1

Flag asking the file functions to search the include path. DIVERGENCE: not honoured — phplang has no include path.

# FILE_APPEND

FILE_APPEND: int = 8

`file_put_contents()` flag appending instead of truncating. This is the one flag that function honours.

# FILE_IGNORE_NEW_LINES

FILE_IGNORE_NEW_LINES: int = 2

`file()` flag stripping the trailing `\n` (and a preceding `\r`) from each line. Honoured.

# FILE_SKIP_EMPTY_LINES

FILE_SKIP_EMPTY_LINES: int = 4

`file()` flag dropping empty lines. Honoured.

# FILE_NO_DEFAULT_CONTEXT

FILE_NO_DEFAULT_CONTEXT: int = 16

Stream-context flag. Defined for compatibility; phplang has no stream contexts.

# LOCK_SH

LOCK_SH: int = 1

Shared advisory lock. DIVERGENCE: there is no `flock()` in this build and `file_put_contents` ignores `LOCK_EX`, so no locking happens anywhere.

# LOCK_EX

LOCK_EX: int = 2

Exclusive advisory lock. Accepted by `file_put_contents` and silently ignored.

# LOCK_UN

LOCK_UN: int = 3

Lock release. Defined for compatibility only.

# LOCK_NB

LOCK_NB: int = 4

Non-blocking lock flag. Defined for compatibility only.

# SEEK_SET

SEEK_SET: int = 0

`fseek` whence: from the start of the stream.

# SEEK_CUR

SEEK_CUR: int = 1

`fseek` whence: from the current position.

# SEEK_END

SEEK_END: int = 2

`fseek` whence: from the end of the stream.

# SCANDIR_SORT_ASCENDING

SCANDIR_SORT_ASCENDING: int = 0

`scandir()` sort order, ascending. The default; sorting is Rust byte order, not PHP's locale collation.

# SCANDIR_SORT_DESCENDING

SCANDIR_SORT_DESCENDING: int = 1

`scandir()` sort order, descending. Honoured.

# SCANDIR_SORT_NONE

SCANDIR_SORT_NONE: int = 2

`scandir()` mode leaving the entries unsorted. DIVERGENCE: not recognized — the result is always sorted.

# PATHINFO_DIRNAME

PATHINFO_DIRNAME: int = 1

`pathinfo()` selector returning just the directory component as a string.

# PATHINFO_BASENAME

PATHINFO_BASENAME: int = 2

`pathinfo()` selector returning just the final component.

# PATHINFO_EXTENSION

PATHINFO_EXTENSION: int = 4

`pathinfo()` selector returning the text after the last dot.

echo pathinfo("a/b.txt", PATHINFO_EXTENSION);   // => txt

# PATHINFO_FILENAME

PATHINFO_FILENAME: int = 8

`pathinfo()` selector returning the basename with its extension removed.

# PATHINFO_ALL

PATHINFO_ALL: int = 15

`pathinfo()` selector returning the full associative array. This is what a call with no second argument produces.

# ENT_NOQUOTES

ENT_NOQUOTES: int = 0

HTML-entity flag leaving both quote characters alone. Read by `get_html_translation_table()`; `htmlspecialchars()` itself ignores its flags argument.

# ENT_COMPAT

ENT_COMPAT: int = 2

HTML-entity flag converting double quotes only.

# ENT_QUOTES

ENT_QUOTES: int = 3

HTML-entity flag converting both quote characters. The default for `get_html_translation_table()`.

# ENT_HTML401

ENT_HTML401: int = 0

Document-type bit selecting HTML 4.01. DIVERGENCE: the doctype bits are not read, so the single quote is always emitted as `&#039;`.

# ENT_HTML5

ENT_HTML5: int = 48

Document-type bit selecting HTML 5. Not honoured.

# ENT_XML1

ENT_XML1: int = 16

Document-type bit selecting XML 1. Not honoured.

# ENT_XHTML

ENT_XHTML: int = 32

Document-type bit selecting XHTML. Not honoured.

# ENT_SUBSTITUTE

ENT_SUBSTITUTE: int = 8

Flag replacing invalid code unit sequences with U+FFFD — part of the default flags, which is why `htmlspecialchars("a\xffb")` is `a�b`.

# ENT_IGNORE

ENT_IGNORE: int = 4

Flag discarding invalid code unit sequences. Without it or `ENT_SUBSTITUTE`, a subject that is not valid UTF-8 encodes to the empty string.

# M_PI

M_PI: float = 3.141592653589793

The ratio of a circle's circumference to its diameter. `pi()` returns the same value.

echo round(M_PI, 4);   // => 3.1416

# M_E

M_E: float = 2.718281828459045

Euler's number, the base of the natural logarithm.

# M_SQRT2

M_SQRT2: float = 1.4142135623730951

The square root of 2.

# M_SQRT1_2

M_SQRT1_2: float = 0.7071067811865476

The square root of 1/2.

# M_SQRT3

M_SQRT3: float = 1.7320508075688772

The square root of 3.

# M_2_SQRTPI

M_2_SQRTPI: float = 1.1283791670955126

Two divided by the square root of pi.

# M_SQRTPI

M_SQRTPI: float = 1.7724538509055159

The square root of pi.

# M_PI_2

M_PI_2: float = 1.5707963267948966

Pi divided by 2.

# M_PI_4

M_PI_4: float = 0.7853981633974483

Pi divided by 4.

# M_1_PI

M_1_PI: float = 0.3183098861837907

One divided by pi.

# M_2_PI

M_2_PI: float = 0.6366197723675814

Two divided by pi.

# M_LN2

M_LN2: float = 0.6931471805599453

The natural logarithm of 2.

# M_LN10

M_LN10: float = 2.302585092994046

The natural logarithm of 10.

# M_LOG2E

M_LOG2E: float = 1.4426950408889634

The base-2 logarithm of e.

# M_LOG10E

M_LOG10E: float = 0.4342944819032518

The base-10 logarithm of e.

# M_EULER

M_EULER: float = 0.5772156649015329

The Euler-Mascheroni constant.

# HASH_HMAC

HASH_HMAC: int = 1

The `hash_init()` flag that makes the context HMAC its input under the key argument.

$c = hash_init("sha256", HASH_HMAC, "k"); echo get_class($c);   // => HashContext

Prelude class

# Exception

class Exception implements Throwable {
    protected $message = ""; protected $code = 0; protected $previous = null;
    protected $file = ""; protected $line = 0; protected $trace = "";
    __construct($message = "", $code = 0, $previous = null)
    final getMessage(): string   final getCode(): int   final getPrevious(): ?Throwable
    final getFile(): string   final getLine(): int   final getTraceAsString(): string
    __toString(): string
}

One of the two disjoint roots of the exception hierarchy. `catch (Throwable)` is special-cased in the host to match this root or `Error`. `file`, `line` and `trace` are recorded when the object is *constructed*, as the reference engine records them, so `getLine()` reports the `new` site even when the `throw` is on a later line. `__toString()` is the reference's rendering: `Class: message in file:line`, `Stack trace:` and the trace, for every exception down the `previous` chain, innermost first and joined by `Next `. DIVERGENCE: `getTrace()` — the structured array form — is not declared; only the rendered `getTraceAsString()` is.

try { throw new Exception("boom", 7); }
catch (Exception $e) { echo $e->getMessage(), $e->getCode(); }   // => boom7

# Error

class Error implements Throwable {
    protected $message = ""; protected $code = 0; protected $previous = null;
    protected $file = ""; protected $line = 0; protected $trace = "";
    __construct($message = "", $code = 0, $previous = null)
    final getMessage(): string   final getCode(): int   final getPrevious(): ?Throwable
    final getFile(): string   final getLine(): int   final getTraceAsString(): string
    __toString(): string
}

The other root of the hierarchy, for engine-level failures. It does NOT extend `Exception` — the two roots are disjoint, exactly as in PHP, so `catch (Exception)` never catches an `Error`. A zero divisor throws `DivisionByZeroError`, and a method call on a non-object throws `Error`. Reaching the top uncaught prints the reference's `Fatal error: Uncaught <__toString()>` block on stdout — a user override of `__toString` included, and an exception that override throws is reported in its place. DIVERGENCE: most other runtime failures — a bad standard-library argument, a call to an undefined function — still abort with a host-level `php: <message>` on stderr that no `catch` block can intercept.

try { throw new TypeError("t"); }
catch (Exception $e) { echo "E"; } catch (Error $e) { echo "R"; }   // => R

# ErrorException

class ErrorException extends Exception { __construct($message = "", $code = 0, $severity = E_ERROR, $filename = null, $line = null, $previous = null); getSeverity(): int }

An exception carrying an error level, the usual way an error handler turns a warning into something `catch` can take. A non-null `$filename` replaces the recorded file and with it the line — `0` when `$line` is null — while a `$line` given alone replaces only the line, as the reference's constructor does.

set_error_handler(fn($n, $s, $f, $l) => throw new ErrorException($s, 0, $n, $f, $l));

# RuntimeException

class RuntimeException extends Exception {}

Thrown for an error only detectable at run time. Adds no members of its own.

# LogicException

class LogicException extends Exception {}

Thrown for an error in the program's logic that should be caught at development time.

# BadFunctionCallException

class BadFunctionCallException extends LogicException {}

Thrown when a callback refers to an undefined function or is called with missing arguments. Adds no members of its own.

# BadMethodCallException

class BadMethodCallException extends BadFunctionCallException {}

Thrown when a callback refers to an undefined method or is called with missing arguments. Adds no members of its own.

# DomainException

class DomainException extends LogicException {}

Thrown when a value does not belong to a defined data domain. Adds no members of its own.

# LengthException

class LengthException extends LogicException {}

Thrown when a length is invalid. Adds no members of its own.

# OutOfRangeException

class OutOfRangeException extends LogicException {}

Thrown for an illegal index requested at compile time. Adds no members of its own.

# OutOfBoundsException

class OutOfBoundsException extends RuntimeException {}

Thrown when a value is not a valid key; `ArrayIterator::seek()` raises it. Adds no members of its own.

# OverflowException

class OverflowException extends RuntimeException {}

Thrown when adding an element to a full container. Adds no members of its own.

# RangeException

class RangeException extends RuntimeException {}

Thrown for a range error at run time. Adds no members of its own.

# UnderflowException

class UnderflowException extends RuntimeException {}

Thrown when removing an element from an empty container. Adds no members of its own.

# UnexpectedValueException

class UnexpectedValueException extends RuntimeException {}

Thrown when a value does not match an expected set of values. Adds no members of its own.

# InvalidArgumentException

class InvalidArgumentException extends LogicException {}

Thrown when an argument does not match the expected type or value.

# CompileError

class CompileError extends Error {}

The parent of `ParseError`, so `catch (CompileError $e)` catches what `eval` throws for unparseable source.

# ParseError

class ParseError extends CompileError {}

Thrown by `eval` for source that does not parse, catchable like any `Error`; a syntax error in the program itself is the fatal `Parse error:` block instead.

# AssertionError

class AssertionError extends Error {}

Declared so user code can construct, throw and catch it.

# ArithmeticError

class ArithmeticError extends Error {}

Thrown for an arithmetic failure, such as a shift by a negative count.

# DivisionByZeroError

class DivisionByZeroError extends ArithmeticError {}

The class raised for a zero divisor. `/` and `intdiv()` throw it with the message `Division by zero`, `%` with `Modulo by zero`, and a program may throw and catch it itself.

try { throw new DivisionByZeroError("x"); }
catch (ArithmeticError $e) { echo get_class($e); }   // => DivisionByZeroError

# TypeError

class TypeError extends Error {}

Thrown when a value has the wrong type for the operation. phplang enforces no declared parameter types, so it is raised far less often than in PHP.

# ValueError

class ValueError extends Error {}

Thrown when a value is of the right type but outside the accepted domain — the class the standard library's range and argument errors report.

# UnhandledMatchError

class UnhandledMatchError extends Error {}

Thrown by a `match` expression whose subject matched no arm and which had no `default`. The message reads `Unhandled match case <subject>`.

try { echo match (5) { 1 => "a" }; }
catch (UnhandledMatchError $e) { echo $e->getMessage(); }   // => Unhandled match case 5

# DateInterval

class DateInterval {
    __construct(string $duration)
    format(string $format): string
    static createFromDateString(string $datetime): DateInterval
}

A duration. The constructor ports `timelib_strtointerval`: `P1Y2M3DT4H5M6S` (weeks fold into days), the combined form `P0001-02-03T04:05:06`, or two ISO date-times whose difference it takes. Its state is the properties the reference shows — `y m d h i s f invert days from_string` — or, for one made by `createFromDateString`, only `from_string` and `date_string`, with the fields still readable. A bad spec throws `DateMalformedIntervalStringException`.

$i = new DateInterval("P1DT2H"); echo $i->d, $i->h;   // => 12

# DateTime

class DateTime implements DateTimeInterface {
    __construct(string $datetime = "now", ?DateTimeZone $timezone = null)
    format  modify  add  sub  diff  getTimestamp  getMicrosecond  getOffset
    getTimezone  setTimezone  setDate  setISODate  setTime  setTimestamp  setMicrosecond
    static createFromFormat  createFromImmutable  createFromInterface  createFromTimestamp  getLastErrors
}

A mutable date and time with microseconds and a zone (an identifier, an offset, or an abbreviation). Each method is a shell over a port of its `php_date.c` routine; the state is the `date`/`timezone_type`/`timezone` properties the reference shows, so `var_dump`, `json_encode`, `serialize` and `clone` agree with it, and two dates compare by instant. A string the scanner refuses throws `DateMalformedStringException`. DIVERGENCE: only fixed-offset zone identifiers resolve (no tz database).

$d = new DateTime("2024-01-31"); echo $d->modify("+1 month")->format("Y-m-d");   // => 2024-03-02

# DateTimeImmutable

class DateTimeImmutable implements DateTimeInterface {
    __construct(string $datetime = "now", ?DateTimeZone $timezone = null)
    (the DateTime API; every mutator returns a new instance)
    static createFromMutable(DateTime $object): static
}

The immutable counterpart of `DateTime`: `modify`, `add`, `sub`, `setTimezone` and the setters each return a NEW instance and leave the receiver untouched.

$a = new DateTimeImmutable("@0"); $b = $a->add(new DateInterval("P1D"));
echo $a->getTimestamp(), " ", $b->getTimestamp();   // => 0 86400

# DateTimeZone

class DateTimeZone {
    __construct(string $timezone)
    getName(): string   getOffset(DateTimeInterface $datetime): int
}

A zone: an identifier, a `±HH:MM` offset, or an abbreviation (`EST`), parsed by timelib's `timelib_parse_zone`; its state is the `timezone_type`/`timezone` properties the reference shows. An unknown zone throws `DateInvalidTimeZoneException`. DIVERGENCE: only fixed-offset identifiers resolve (no tz database).

echo (new DateTimeZone("+05:30"))->getOffset(new DateTime("@0"));   // => 19800

# stdClass

class stdClass {}

The empty generic object. Properties are added dynamically at assignment. Produced by `new stdClass` and by the `(object)` cast. DIVERGENCE: `json_decode` always yields arrays, so it never produces one.

$o = new stdClass; $o->x = 1; echo $o->x, get_class($o);   // => 1stdClass

# SplDoublyLinkedList

class SplDoublyLinkedList implements Iterator, Countable, ArrayAccess, Serializable {
    const IT_MODE_LIFO = 2; const IT_MODE_FIFO = 0; const IT_MODE_DELETE = 1; const IT_MODE_KEEP = 0;
    add  pop  shift  push  unshift  top  bottom  count  isEmpty
    setIteratorMode  getIteratorMode  offsetExists  offsetGet  offsetSet  offsetUnset
    rewind  current  key  prev  next  valid  serialize  __serialize  __unserialize  __debugInfo
}

A port of `ext/spl/spl_dllist.c`: the iterator modes (FIFO/LIFO, KEEP/DELETE), offsets counted from the tail in LIFO mode, the reference's `RuntimeException` / `OutOfRangeException` messages, `__serialize` as `[flags, elements, members]`, and `var_dump`/`print_r` showing `flags` and `dllist` through `__debugInfo`. DIVERGENCE: the list is held in private properties, so `(array)` and `var_export` show them where the reference shows none; the legacy `unserialize(string)` method restores nothing; `foreach` moves the object's own cursor rather than a separate iterator's.

$l = new SplDoublyLinkedList; $l->push(1); $l->push(2);
echo $l->count(), $l->top();   // => 22

# SplStack

class SplStack extends SplDoublyLinkedList {}

A `SplDoublyLinkedList` whose iteration is fixed to LIFO (`getIteratorMode()` is 6): `foreach` and `$s[0]` start from the top. Asking for FIFO is the reference's `RuntimeException`.

$s = new SplStack; $s->push(1); $s->push(2); echo $s->pop();   // => 2

# SplQueue

class SplQueue extends SplDoublyLinkedList {
    enqueue(mixed $value): void   dequeue(): mixed
}

A `SplDoublyLinkedList` whose iteration is fixed to FIFO: `enqueue()` is `push()` and `dequeue()` is `shift()`.

$q = new SplQueue; $q->enqueue(1); $q->enqueue(2); echo $q->dequeue();   // => 1

# SplFixedArray

class SplFixedArray implements IteratorAggregate, ArrayAccess, Countable, JsonSerializable {
    __construct(int $size = 0)   count  toArray  fromArray(array $array, bool $preserveKeys = true)
    getSize  setSize  offsetExists  offsetGet  offsetSet  offsetUnset  getIterator  jsonSerialize
    __serialize  __unserialize  __debugInfo
}

A port of `ext/spl/spl_fixedarray.c`: offsets convert as `spl_offset_convert_to_ulong` does, an index past either end is `OutOfBoundsException: Index invalid or out of range`, a negative size is the reference's `ValueError`, and `var_dump`/`json_encode`/`serialize` show the elements. DIVERGENCE: the elements are a private property, so `(array)` and `var_export` show it; `$f[] = $v` reports the offset `TypeError` rather than `[] operator not supported`; `getIterator()` answers an `ArrayIterator`.

$a = new SplFixedArray(3); $a[0] = "x";
echo $a->getSize(), $a[0];   // => 3x

# ArrayObject

class ArrayObject implements IteratorAggregate, ArrayAccess, Serializable, Countable {
    private $storage = [];
    __construct(array|object $array = [], int $flags = 0, string $iteratorClass = ArrayIterator::class)
    offsetGet  offsetSet  offsetExists  offsetUnset  append  count  getArrayCopy  exchangeArray
    getIterator(): Iterator  asort  ksort  uasort  uksort  natsort  natcasesort  serialize  unserialize
}

An object wrapper around an array: `$obj[$k]`, `count($obj)` and `foreach` reach the wrapped array, and `getIterator()` hands out an `ArrayIterator` over a copy of it. An object passed in (deprecated since 8.5) is wrapped, not copied: reads and writes reach its properties, `$obj[] = v` adds an integer-keyed property, and `count`/`foreach` skip its non-public ones while `getArrayCopy()` returns the whole table. `getIterator()` shares the storage. DIVERGENCE: the `STD_PROP_LIST` flag is accepted and ignored.

$o = new ArrayObject(["a" => 1]); $o->append(2);
echo $o->count(), $o->offsetGet("a");   // => 21

# ArrayIterator

class ArrayIterator implements SeekableIterator, ArrayAccess, Serializable, Countable {
    private $storage = [];
    current()  key()  next()  rewind()  valid()  seek(int $offset)
    offsetGet  offsetSet  offsetExists  offsetUnset  append  count  getArrayCopy  asort  ksort  serialize  unserialize ...
}

An iterator over an array, with the array access and sorting of `ArrayObject`. `seek()` past the end throws `OutOfBoundsException`. `getFlags()` answers the flags the constructor or `setFlags()` set, and `ARRAY_AS_PROPS` makes a missing property an element. An object passed in (deprecated since 8.5) is wrapped as `ArrayObject` wraps one. DIVERGENCE: `STD_PROP_LIST` is accepted and ignored, and a write while iterating restarts the key order the cursor walks.

$it = new ArrayIterator([10, 20, 30]); $it->seek(1);
echo $it->current();   // => 20

# IteratorIterator

class IteratorIterator implements OuterIterator {
    __construct(Traversable $iterator, ?string $class = null)
    getInnerIterator  rewind  valid  key  current  next
}

A port of `ext/spl/spl_iterators.c`'s dual iterator, the base of the iterators below: it caches the inner iterator's current value and key at each step (`spl_dual_it_fetch`), wraps an `IteratorAggregate` in the iterator its `getIterator()` answers, and forwards a method it does not have to the inner iterator (`spl_dual_it_get_method`). Constructing one twice is `BadMethodCallException`; a subclass that never called the constructor gets `Error: The object is in an invalid state as the parent constructor was not called`. An instance shows no properties.

$it = new IteratorIterator(new ArrayObject([1, 2]));
foreach ($it as $k => $v) echo "$k=$v ";   // => 0=1 1=2

# FilterIterator

abstract class FilterIterator extends IteratorIterator {
    abstract accept(): bool
    __construct(Iterator $iterator)   rewind  next
}

Skips every element whose `accept()` answers false, calling it once per inner element as `spl_filter_it_fetch` does.

class Odd extends FilterIterator { function accept(): bool { return $this->current() % 2 == 1; } }
echo implode(",", iterator_to_array(new Odd(new ArrayIterator([1, 2, 3])), false));   // => 1,3

# CallbackFilterIterator

class CallbackFilterIterator extends FilterIterator {
    __construct(Iterator $iterator, callable $callback)   accept
}

A `FilterIterator` whose `accept()` calls `$callback($current, $key, $iterator)`.

$f = new CallbackFilterIterator(new ArrayIterator([1, 2, 3]), fn($v) => $v != 2);
echo implode(",", iterator_to_array($f, false));   // => 1,3

# RecursiveFilterIterator

abstract class RecursiveFilterIterator extends FilterIterator implements RecursiveIterator {
    __construct(RecursiveIterator $iterator)   hasChildren  getChildren
}

A `FilterIterator` over a `RecursiveIterator`: `getChildren()` wraps the inner iterator's children in a new instance of the same class.

# RecursiveCallbackFilterIterator

class RecursiveCallbackFilterIterator extends CallbackFilterIterator implements RecursiveIterator {
    __construct(RecursiveIterator $iterator, callable $callback)   hasChildren  getChildren
}

The recursive `CallbackFilterIterator`: children are filtered by the same callback.

# ParentIterator

class ParentIterator extends RecursiveFilterIterator {
    __construct(RecursiveIterator $iterator)   accept
}

Accepts only the elements that have children.

# LimitIterator

class LimitIterator extends IteratorIterator {
    __construct(Iterator $iterator, int $offset = 0, int $limit = -1)
    rewind  valid  next  seek(int $offset): int  getPosition
}

A window of `$limit` elements starting at `$offset`, as `spl_limit_it_seek` walks it: a `SeekableIterator` is sought, anything else is stepped (rewinding first to go back). A position outside the window is `OutOfBoundsException`; a negative offset or a limit below -1 is a `ValueError`.

$l = new LimitIterator(new ArrayIterator([1, 2, 3, 4, 5]), 1, 2);
echo implode(",", iterator_to_array($l, false));   // => 2,3

# CachingIterator

class CachingIterator extends IteratorIterator implements ArrayAccess, Countable, Stringable {
    __construct(Iterator $iterator, int $flags = CachingIterator::CALL_TOSTRING)
    rewind  valid  next  hasNext  __toString  getFlags  setFlags
    offsetGet  offsetSet  offsetUnset  offsetExists  getCache  count
}

Runs one element ahead of its inner iterator, so `hasNext()` can answer whether the current element is the last. `CALL_TOSTRING`, `TOSTRING_USE_KEY`, `TOSTRING_USE_CURRENT` and `TOSTRING_USE_INNER` pick what `__toString` answers (at most one of them); `FULL_CACHE` keeps every element for array access, `getCache()` and `count()`. Messages and flag rules are `ext/spl`'s.

$c = new CachingIterator(new ArrayIterator(["a", "b"]));
foreach ($c as $v) echo $v, $c->hasNext() ? "," : "\n";   // => a,b

# RecursiveCachingIterator

class RecursiveCachingIterator extends CachingIterator implements RecursiveIterator {
    __construct(Iterator $iterator, int $flags = RecursiveCachingIterator::CALL_TOSTRING)
    hasChildren  getChildren
}

A `CachingIterator` over a `RecursiveIterator`: the children of each element are fetched as it is cached, and handed out as a `RecursiveCachingIterator` with the same flags. `CATCH_GET_CHILD` swallows an exception from fetching them.

# NoRewindIterator

class NoRewindIterator extends IteratorIterator {
    __construct(Iterator $iterator)   rewind  valid  key  current  next
}

Passes every step to the inner iterator except `rewind()`, so a second `foreach` continues where the first stopped.

# InfiniteIterator

class InfiniteIterator extends IteratorIterator {
    __construct(Iterator $iterator)   next
}

Rewinds the inner iterator when it runs out, forever.

$n = 0; foreach (new InfiniteIterator(new ArrayIterator([1, 2])) as $v) { echo $v; if (++$n == 5) break; }   // => 12121

# AppendIterator

class AppendIterator extends IteratorIterator {
    __construct()   append(Iterator $iterator)   rewind  valid  current  next
    getIteratorIndex  getArrayIterator
}

Walks several iterators one after another. The iterators are kept in an `ArrayIterator`, which `getArrayIterator()` answers; `getIteratorIndex()` is the position of the one being walked.

$a = new AppendIterator; $a->append(new ArrayIterator([1])); $a->append(new ArrayIterator([2]));
echo implode(",", iterator_to_array($a, false));   // => 1,2

# EmptyIterator

class EmptyIterator implements Iterator {
    current  next  key  valid  rewind
}

Never valid; `current()` and `key()` throw `BadMethodCallException`.

# RegexIterator

class RegexIterator extends FilterIterator {
    const USE_KEY, INVERT_MATCH, MATCH, GET_MATCH, ALL_MATCHES, SPLIT, REPLACE
    public ?string $replacement = null
    __construct(Iterator $iterator, string $pattern, int $mode = RegexIterator::MATCH, int $flags = 0, int $pregFlags = 0)
    accept  getMode  setMode  getFlags  setFlags  getRegex  getPregFlags  setPregFlags
}

Filters by a regular expression matched against each element (or its key, with `USE_KEY`): `MATCH` tests it, `GET_MATCH` / `ALL_MATCHES` / `SPLIT` replace the element by what `preg_match` / `preg_match_all` / `preg_split` answer, and `REPLACE` substitutes `$replacement`. A pattern that does not compile is an `InvalidArgumentException` carrying the PCRE message.

$r = new RegexIterator(new ArrayIterator(["a1", "b", "c2"]), "/\\d/");
echo implode(",", iterator_to_array($r, false));   // => a1,c2

# RecursiveRegexIterator

class RecursiveRegexIterator extends RegexIterator implements RecursiveIterator {
    __construct(RecursiveIterator $iterator, string $pattern, int $mode = RecursiveRegexIterator::MATCH, int $flags = 0, int $pregFlags = 0)
    accept  hasChildren  getChildren
}

The recursive `RegexIterator`; an element that is a non-empty array is accepted as it is.

# RecursiveArrayIterator

class RecursiveArrayIterator extends ArrayIterator implements RecursiveIterator {
    const CHILD_ARRAYS_ONLY = 4
    hasChildren  getChildren
}

An `ArrayIterator` whose array and object elements have children, iterated by a new instance of the same class (an element that already is one is answered as it is). `CHILD_ARRAYS_ONLY` leaves objects childless.

# RecursiveIteratorIterator

class RecursiveIteratorIterator implements OuterIterator {
    const LEAVES_ONLY = 0, SELF_FIRST = 1, CHILD_FIRST = 2, CATCH_GET_CHILD = 16
    __construct(Traversable $iterator, int $mode = RecursiveIteratorIterator::LEAVES_ONLY, int $flags = 0)
    rewind  valid  key  current  next  getDepth  getSubIterator  getInnerIterator
    beginIteration  endIteration  callHasChildren  callGetChildren  beginChildren  endChildren  nextElement
    setMaxDepth  getMaxDepth
}

A port of `spl_recursive_it_move_forward_ex`: a depth-first walk of a `RecursiveIterator` in one of three orders, down to `setMaxDepth()` levels, calling a subclass's hooks where the reference does. `CATCH_GET_CHILD` swallows an exception from `hasChildren()`/`getChildren()`. A method it does not have is forwarded to the iterator of the level being walked.

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator([1, [2, [3]], 4]));
echo implode(",", iterator_to_array($it, false));   // => 1,2,3,4

# RecursiveTreeIterator

class RecursiveTreeIterator extends RecursiveIteratorIterator {
    const BYPASS_CURRENT = 4, BYPASS_KEY = 8, PREFIX_LEFT = 0 … PREFIX_RIGHT = 5
    __construct(RecursiveIterator|IteratorAggregate $iterator, int $flags = RecursiveTreeIterator::BYPASS_KEY, int $cachingIteratorFlags = CachingIterator::CATCH_GET_CHILD, int $mode = RecursiveTreeIterator::SELF_FIRST)
    key  current  getPrefix  setPostfix  setPrefixPart  getEntry  getPostfix
}

Draws the walk as an ASCII tree: each element is prefixed with `| `, ` `, `|-` and `\-` by whether the iterator at each level has more elements, over a `RecursiveCachingIterator` of the input.

$t = new RecursiveTreeIterator(new RecursiveArrayIterator(["a" => [1], "b" => 2]));
echo implode(" / ", iterator_to_array($t, false));   // => |-Array / | \-1 / \-2

# SplObjectStorage

class SplObjectStorage implements Countable, SeekableIterator, Serializable, ArrayAccess {
    attach  detach  contains  addAll  removeAll  removeAllExcept  getInfo  setInfo  count
    rewind  valid  key  current  next  seek  offsetExists  offsetGet  offsetSet  offsetUnset
    getHash  serialize  unserialize  __serialize  __unserialize  __debugInfo
}

A port of `ext/spl/spl_observer.c`: a set of objects with attached data, keyed by object handle — or by the string a subclass's `getHash()` answers — in insertion order, iterated by its own pointer and index. A missing object is `UnexpectedValueException: Object not found`; `var_dump`, `print_r` and `serialize` show the reference's `storage` view. DIVERGENCE: `attach()`/`detach()`/`contains()` raise no 8.5 deprecation; `unserialize()` (the `Serializable` form) does nothing; `(array)` and `var_export` show the private properties the elements are kept in.

$s = new SplObjectStorage; $o = new stdClass; $s[$o] = "data";
var_dump($s[$o], count($s));   // => string(4) "data" int(1)

# SplPriorityQueue

class SplPriorityQueue implements Iterator, Countable {
    const EXTR_BOTH = 3; const EXTR_PRIORITY = 2; const EXTR_DATA = 1;
    compare  insert  setExtractFlags  getExtractFlags  top  extract  count  isEmpty
    rewind  current  key  next  valid  recoverFromCorruption  isCorrupted  __serialize  __unserialize  __debugInfo
}

A port of `ext/spl/spl_heap.c`'s priority queue: a binary heap with the reference's sift-up and delete-top walks, so equal priorities come out in the reference's order, the extract flags, and the corruption state a throwing `compare()` leaves. Iterating consumes the queue.

$q = new SplPriorityQueue; $q->insert("lo", 1); $q->insert("hi", 9);
echo $q->extract();   // => hi

# SplHeap

abstract class SplHeap implements Iterator, Countable {
    abstract protected compare(mixed $value1, mixed $value2): int
    extract  insert  top  count  isEmpty  rewind  current  key  next  valid
    recoverFromCorruption  isCorrupted  __serialize  __unserialize  __debugInfo
}

A port of `ext/spl/spl_heap.c`: a binary heap ordered by `compare()`, with the reference's sift walks, `Can't extract from an empty heap` / `Can't peek at an empty heap`, and a `compare()` that throws leaving the heap corrupted until `recoverFromCorruption()`. Abstract: extend it and implement `compare()`.

class H extends SplHeap { protected function compare($a, $b): int { return $a <=> $b; } }
$h = new H; $h->insert(3); $h->insert(9); echo $h->extract();   // => 9

# SplMaxHeap

class SplMaxHeap extends SplHeap {
    protected compare(mixed $value1, mixed $value2): int   //  $value1 <=> $value2
}

A heap whose `extract()` yields the largest element first.

$h = new SplMaxHeap; $h->insert(1); $h->insert(5); echo $h->extract();   // => 5

# SplMinHeap

class SplMinHeap extends SplHeap {
    protected compare(mixed $value1, mixed $value2): int   //  $value2 <=> $value1
}

A heap whose `extract()` yields the smallest element first.

$h = new SplMinHeap; $h->insert(5); $h->insert(1); echo $h->extract();   // => 1

# HashContext

final class HashContext {
    private __construct()
    __debugInfo(): array   //  ["algo" => "sha256"]
}

The state of an incremental hash, created only by `hash_init()` or `hash_copy()` and consumed by `hash_update()`, `hash_update_stream()`, `hash_update_file()` and `hash_final()`. `var_dump` and `print_r` show its algorithm, as the reference's do; `clone` copies the state. DIVERGENCE: `(array)` and `var_export` show the prelude's private properties, where the reference shows none; `serialize` is not the reference's form.

$c = hash_init("sha256"); var_dump($c);   // => object(HashContext)#1 (1) { ["algo"]=> string(6) "sha256" }

# ReflectionClass

class ReflectionClass {
    public string $name;
    __construct(object|string $objectOrClass)
    getName()  getShortName()  getNamespaceName()  inNamespace()
    isInterface()  isTrait()  isEnum()  isAbstract()  isFinal()  isInstantiable()  isInternal()  isUserDefined()  isAnonymous()
    getParentClass()  getInterfaceNames()  getInterfaces()  getTraitNames()  implementsInterface()  isSubclassOf()  isInstance()
    hasMethod()  getMethod()  getMethods(?int $filter)  getConstructor()
    hasProperty()  getProperty()  getProperties(?int $filter)  getDefaultProperties()  getStaticProperties()  getStaticPropertyValue()  setStaticPropertyValue()
    hasConstant()  getConstant()  getConstants()  getReflectionConstant()
    newInstance(...$args)  newInstanceArgs(array $args)  newInstanceWithoutConstructor()
}

A class, interface, trait or enum by name or by instance; `ReflectionException: Class "X" does not exist` otherwise. Methods and properties are listed own first (a trait's included) in declaration order, then each ancestor's not overridden — an ancestor's private members are not inherited — and an abstract class lists its interfaces' methods; constants list an enum's cases first. Made from an object, `hasProperty` also sees its dynamic properties. `getDocComment()` answers the `/** … */` comment the declaration took — the last one before it, unless a `{` or `}` came between or an earlier declaration took it — for a class, function, method, closure, property, constant or enum case, else `false`. `getAttributes()` answers `ReflectionAttribute`s. DIVERGENCE: `getFileName()` answers `false`, and there is no `__toString()`.

class A { public $x = 1; } echo (new ReflectionClass("A"))->getProperties()[0]->name;   // => x

# ReflectionObject

class ReflectionObject extends ReflectionClass { __construct(object $object) }

`ReflectionClass` made from an instance.

# ReflectionAttribute

final class ReflectionAttribute { const IS_INSTANCEOF = 2; getName()  getArguments()  getTarget()  isRepeated()  newInstance() }

One `#[…]` attribute of a class, function, method, closure, property, class constant, enum case or parameter, as that declaration's `getAttributes(?string $name = null, int $flags = 0)` lists them — filtered to one name, or with `IS_INSTANCEOF` to the subclasses of one (`Error: Class "X" not found` if it does not exist); any other flag is `ValueError: …::getAttributes(): Argument #2 ($flags) must be a valid attribute filter flag`. `getArguments()` evaluates the arguments when asked, in the declaring class's scope, positional then named. `newInstance()` refuses a missing class (`Attribute class "X" not found`), a class without `#[Attribute]` (`Attempting to use non-attribute class "X" as attribute`), a target its flags exclude (`Attribute "X" cannot target method (allowed targets: class)`) and a repeat without `IS_REPEATABLE` (`Attribute "X" must not be repeated`). The internal attribute classes (`Attribute`, `Deprecated`, `Override`, `SensitiveParameter`, `AllowDynamicProperties`, `ReturnTypeWillChange`, `NoDiscard`) carry their reference flags.

# ReflectionEnum

class ReflectionEnum extends ReflectionClass { isBacked()  getCases()  hasCase()  getCase() }
class ReflectionEnumUnitCase extends ReflectionClassConstant { getEnum()  getValue() }
class ReflectionEnumBackedCase extends ReflectionEnumUnitCase { getBackingValue() }

`ReflectionClass` of an enum; `ReflectionException` for anything else. `getCases()` and `getCase()` answer `ReflectionEnumUnitCase` (`ReflectionEnumBackedCase` for a backed enum) objects; a constant that is not a case, a missing case, and a pure case asked for as backed are the reference's `ReflectionException`s.

# ReflectionMethod

class ReflectionMethod extends ReflectionFunctionAbstract {
    public string $name; public string $class;
    __construct(object|string $objectOrMethod, ?string $method = null)
    static createFromMethodName(string $method)
    getModifiers()  isPublic()  isProtected()  isPrivate()  isStatic()  isFinal()  isAbstract()  isConstructor()
    getDeclaringClass()  invoke(?object $object, ...$args)  invokeArgs(?object $object, array $args)  getClosure()
}

A method, found along the class's chain (an ancestor's private one included). `invoke` runs it from the declaring class's scope, so a private method can be called; `setAccessible()` has no effect and is deprecated, and the one-argument `"C::m"` constructor is deprecated in favour of `createFromMethodName`, as in 8.5.

# ReflectionProperty

class ReflectionProperty {
    public string $name; public string $class;
    __construct(object|string $class, string $property)
    getModifiers()  isPublic()  isProtected()  isPrivate()  isStatic()  isReadOnly()  isFinal()
    hasType()  getType()  hasDefaultValue()  getDefaultValue()  getDeclaringClass()
    getValue(?object $object)  setValue($objectOrValue, $value)  isInitialized(?object $object)
}

A property, read and written from the declaring class's scope so its visibility does not stand in the way. The modifiers carry the write visibility (`protected(set)` for a public readonly property). A one-argument `setValue` on a static property is deprecated, as in 8.5.

# ReflectionFunction

class ReflectionFunction extends ReflectionFunctionAbstract {
    __construct(Closure|string $function)
    isInternal()  isClosure()  invoke(...$args)  invokeArgs(array $args)  getClosure()
}

A user function, a library function or a closure; `ReflectionException: Function f() does not exist` otherwise. `ReflectionFunctionAbstract` supplies `getName()`, `getShortName()`, `getNamespaceName()`, `getParameters()`, `getNumberOfParameters()`, `getNumberOfRequiredParameters()`, `isVariadic()`, `hasReturnType()` and `getReturnType()`. DIVERGENCE: a library function's return type is read from this corpus's signature, which does not always spell the reference's union.

# ReflectionParameter

class ReflectionParameter {
    public string $name;
    getName()  getPosition()  isOptional()  isVariadic()  isPassedByReference()  canBePassedByValue()
    hasType()  getType()  allowsNull()  isDefaultValueAvailable()  getDefaultValue()  getDeclaringFunction()  getDeclaringClass()
}

One parameter. A parameter is optional once no required one follows it. `getDefaultValue()` evaluates the default where it was declared; a library function's comes from the argument tables.

# ReflectionNamedType

class ReflectionNamedType extends ReflectionType { getName()  isBuiltin()  allowsNull()  __toString() }

A declared type with one alternative besides `null`: `?I` names `I` and allows null. `self` inside a class names the class. A type of several alternatives is a `ReflectionUnionType`, whose `getTypes()` lists them in the order the type prints in.

# ReflectionUnionType

class ReflectionUnionType extends ReflectionType { getTypes()  allowsNull()  __toString() }

A union type, printed and listed in the reference's order — class names, then the built-in types in the engine's fixed order, `null` last.

# ReflectionClassConstant

class ReflectionClassConstant { public string $name; public string $class; getName()  getValue()  getDeclaringClass() }

One class constant.

# ReflectionException

class ReflectionException extends Exception {}

What the reflection constructors throw for a name that does not exist.

# Reflection

class Reflection { static getModifierNames(int $modifiers): array }

The modifier names, in the reference's order: `abstract`, `final`, the visibility, the write visibility, `static`, `readonly`.

var_dump(Reflection::getModifierNames(17));   // => array(2) { [0]=> "public" [1]=> "static" }

Core library — strings

# strlen

strlen(string $string): int

Length of the string in BYTES, not characters — `strlen("héllo")` is 6. Use `mb_strlen()` for the codepoint count.

echo strlen("abc"), " ", strlen("héllo");   // => 3 6

# strtoupper

strtoupper(string $string): string

Uppercases the ASCII letters in the string, leaving every other byte alone — so `strtoupper("héllo")` is `"HéLLO"`, as in PHP 8. Use `mb_strtoupper` for the Unicode-aware form.

echo strtoupper("abc");   // => ABC

# strtolower

strtolower(string $string): string

Lowercases the string with Rust's full Unicode `to_lowercase`, with the same non-ASCII divergence from PHP as `strtoupper`.

echo strtolower("ABC");   // => abc

# ucfirst

ucfirst(string $string): string

Uppercases the first character and leaves the rest untouched. The conversion is full Unicode, so the first character may expand to several codepoints.

echo ucfirst("hello");   // => Hello

# lcfirst

lcfirst(string $string): string

Lowercases the first character and leaves the rest untouched.

echo lcfirst("Hello");   // => hello

# ucwords

ucwords(string $string): string

Uppercases the first letter of each word. Words are separated by whitespace only — the `$separators` argument PHP accepts is not read, so `-` and `.` do not start a new word.

echo ucwords("hello world-foo");   // => Hello World-foo

# trim

trim(string $string): string

Removes leading and trailing characters, defaulting to PHP's set `" \t\n\r\0\x0B"`. The optional `$characters` argument replaces that set and understands `a..z` inclusive ranges; a malformed range warns `trim(): Invalid '..'-range, …` and contributes nothing. Byte-oriented.

echo trim("  hi  ");   // => hi

# ltrim

ltrim(string $string): string

Removes leading whitespace only. The `$characters` argument is not read.

echo ltrim("  hi");   // => hi

# rtrim

rtrim(string $string): string

Removes trailing whitespace only. The `$characters` argument is not read.

echo rtrim("hi  ") . "!";   // => hi!

# chop

chop(string $string): string

The historical alias of `rtrim`, sharing its match arm and therefore its behaviour exactly.

# str_repeat

str_repeat(string $string, int $times): string

Concatenates the string with itself `$times` times. A count of zero yields the empty string; a negative count throws `ValueError: str_repeat(): Argument #2 ($times) must be greater than or equal to 0`. When `strlen * $times + 32` overflows the address space the engine stops with the UNCATCHABLE fatal `Possible integer overflow in memory allocation (len * times + 32)`, as the reference does.

echo str_repeat("ab", 3);   // => ababab

# str_shuffle

str_shuffle(string $string): string

A random permutation of the string, by the reference's own walk over the shared Mt19937 engine, so a seeded program gets the reference's permutation. DIVERGENCE: the permutation is of CHARACTERS, not bytes — identical for ASCII; the reference would split a multibyte character.

mt_srand(3); echo str_shuffle("abcdef");   // => fcabde

# strrev

strrev(string $string): string

Reverses the string's BYTES, as PHP does — a multibyte character comes out with its bytes reversed.

echo strrev("abc");   // => cba

# wordwrap

wordwrap(string $string, int $width = 75, string $break = "\n", bool $cut = false): string

Wraps the text to `$width` columns, breaking at spaces. With `$cut` true a word longer than the width is split rather than left overlong; a zero `$width` with `$cut` true has no answer and raises `ValueError: wordwrap(): Argument #4 ($cut_long_words) cannot be true when argument #2 ($width) is 0`.

echo wordwrap("a b c", 3, "|", true);   // => a b|c

# substr

substr(string $string, int $offset, ?int $length = null): string

A substring counted in BYTES. A negative offset counts from the end and a negative length omits that many trailing bytes; a cut through a multibyte character keeps its bytes. It never returns `false`.

echo substr("hello", 1, 3);   // => ell

# strpos

strpos(string $haystack, string $needle): int|false

BYTE offset of the first occurrence at or after `$offset`, or `false` when absent. A negative `$offset` counts from the end; one outside `[-strlen, strlen]` raises `ValueError: strpos(): Argument #3 ($offset) must be contained in argument #1 ($haystack)` rather than reporting no match. An empty needle returns the offset itself.

var_dump(strpos("hello", "l"), strpos("hello", "z"));   // => int(2) bool(false)

# str_replace

str_replace(string $search, string $replace, string $subject): string

Replaces every occurrence of the search string. `$search`/`$replace` may be arrays (paired by position, or one replacement for every needle), an array `$subject` is processed element-wise, and the by-reference `$count` receives the number of replacements.

echo str_replace("a", "b", "aaa");   // => bbb

# str_split

str_split(string $string, int $length = 1): array

Splits the string into chunks of `$length` characters; the last chunk may be shorter.

echo str_split("ab")[0];   // => a

# str_pad

str_pad(string $string, int $length, string $pad = " ", int $type = STR_PAD_RIGHT): string

Pads the string to `$length` by cycling `$pad`. `STR_PAD_RIGHT`, `STR_PAD_LEFT`, and `STR_PAD_BOTH` are all honoured; a string already at least that long is returned unchanged.

echo str_pad("5", 3, "0"), " ", str_pad("5", 3, "0", STR_PAD_LEFT);   // => 500 005

# str_contains

str_contains(string $haystack, string $needle): bool

True when the haystack contains the needle. An empty needle is always found.

var_dump(str_contains("hello", "ell"));   // => bool(true)

# str_starts_with

str_starts_with(string $haystack, string $needle): bool

True when the haystack begins with the needle.

var_dump(str_starts_with("hello", "he"));   // => bool(true)

# str_ends_with

str_ends_with(string $haystack, string $needle): bool

True when the haystack ends with the needle.

var_dump(str_ends_with("hello", "lo"));   // => bool(true)

# number_format

number_format(float $num, int $decimals = 0, string $decimal_separator = ".", string $thousands_separator = ","): string

Formats a number with grouped thousands and a fixed number of decimals, rounding half away from zero.

echo number_format(1234.567, 2);   // => 1,234.57

# htmlspecialchars

htmlspecialchars(string $string): string

Escapes `&`, `<`, `>`, and — as `$flags` selects — `"` (`ENT_COMPAT`) and `'` (`ENT_QUOTES`, the default since PHP 8.1, written as the numeric `&#039;` under `ENT_HTML401`). DIVERGENCE: `$encoding` and `$double_encode` are not read, so `&` is always re-encoded.

echo htmlspecialchars("a<b");   // => a&lt;b

# htmlentities

htmlentities(string $string): string

`htmlspecialchars` plus the full HTML 4.01 named-entity table, so `é` becomes `&eacute;`, `€` `&euro;`, and `α` `&alpha;`. `$flags` selects quote handling as it does there. DIVERGENCE: `$encoding` and `$double_encode` are not read.

echo htmlentities("café");   // => caf&eacute;

# strcmp

strcmp(string $string1, string $string2): int

Byte comparison returning only the sign: `-1`, `0`, or `1`. PHP 8 also normalizes to the sign, so this matches.

echo strcmp("a", "b");   // => -1

# strcasecmp

strcasecmp(string $string1, string $string2): int

Compares after lowercasing both operands with full Unicode folding, returning `-1`, `0`, or `1`.

echo strcasecmp("A", "a");   // => 0

# strncmp

strncmp(string $string1, string $string2, int $length): int

Compares at most the first `$length` BYTES of each string, returning the sign. A length beyond either string simply compares what is there.

echo strncmp("abcd", "abzz", 2);   // => 0

# substr_compare

substr_compare(string $haystack, string $needle, int $offset, ?int $length = null, bool $case_insensitive = false): int

Compares `$needle` against the slice of `$haystack` starting at `$offset` (negatives count from the end), over `$length` bytes or, when that is null, `max(strlen($needle), strlen($haystack) - $offset)`. The result is NOT normalized: differing bytes answer their signed difference, and only a tie on content falls back to -1/0/1 on length. An `$offset` past the haystack, or a negative `$length`, throws `ValueError`; a `$length` of 0 answers 0.

echo substr_compare("Hello", "llo", 2);   // => 0

# chr

chr(int $codepoint): string

The one-character string for a byte value, reduced modulo 256 so any integer is accepted — a value outside `0..=255` raises `Deprecated: chr(): Providing a value not in-between 0 and 255 is deprecated…` first. The result is that one BYTE: `strlen(chr(233))` is 1.

echo chr(65);   // => A

# ord

ord(string $character): int

The value of the first BYTE of the string, so a multibyte character reports its leading byte (`ord("é")` is 195). The empty string returns 0 and raises `Deprecated: ord(): Providing an empty string is deprecated`.

echo ord("A");   // => 65

# dechex

dechex(int $num): string

Lowercase hexadecimal rendering of an integer. DIVERGENCE: a negative number renders as `-` plus the magnitude, where PHP renders the unsigned 64-bit two's-complement form.

echo dechex(255);   // => ff

# hexdec

hexdec(string $hex_string): int

The integer value of a hexadecimal string, after trimming surrounding whitespace. A leading `0x`/`0X` is dropped. Characters that are not hex digits are skipped, and skipping ANY raises `Deprecated: Invalid characters passed for attempted conversion, these have been ignored` before returning. The result is an integer when it fits `PHP_INT_MAX` and a float otherwise.

echo hexdec("ff");   // => 255

# bin2hex

bin2hex(string $string): string

Two lowercase hex digits per byte of the string.

echo bin2hex("AB");   // => 4142

# sprintf

sprintf(string $format, mixed ...$values): string

Formats the arguments into a string. Supports the `%b %c %d %u %e %E %f %F %g %G %o %s %x %X %%` conversions with width, precision, `-` left-align, `0` and `'` custom padding, `+` sign, and `%n$` argument reordering.

echo sprintf("%05.2f|%s|%x|%b", 3.14159, "s", 255, 5);   // => 03.14|s|ff|101

Core library — arrays

# count

count(Countable|array $value, int $mode = COUNT_NORMAL): int

Number of elements in an array, or what a `Countable`'s own `count()` returns. Anything else is a `TypeError` — PHP 8 stopped answering 1 for a scalar. `$mode` is `COUNT_NORMAL` or `COUNT_RECURSIVE`, and any other value is a `ValueError`.

echo count([1, 2, 3]);   // => 3

# sizeof

sizeof(Countable|array $value, int $mode = COUNT_NORMAL): int

The alias of `count`, sharing its match arm and therefore its modes and its errors exactly.

# array_keys

array_keys(array $array): array

A new list of the array's keys in insertion order. DIVERGENCE: the `$filter_value` and `$strict` arguments are not read, so the filtered form is unavailable.

echo implode(",", array_keys(["a" => 1, "b" => 2]));   // => a,b

# array_values

array_values(array $array): array

A new list of the array's values, reindexed from 0.

echo implode(",", array_values([5 => "a", 9 => "b"]));   // => a,b

# array_push

array_push(array $array, mixed ...$values): int

Appends each value with the next integer key and returns the new element count. The array is a shared handle, so the caller's variable sees the change.

$a = [1]; array_push($a, 2); echo implode(",", $a);   // => 1,2

# in_array

in_array(mixed $needle, array $haystack, bool $strict = false): bool

True when the value occurs in the array, comparing loosely by default and with `===` when `$strict` is truthy.

var_dump(in_array("2", [1, 2, 3], true));   // => bool(false)

# range

range(mixed $start, mixed $end, int|float $step = 1): array

An inclusive sequence, ported from `PHP_FUNCTION(range)`. `$step` is validated FIRST and independently of the bounds, with a distinct message for each fault: `cannot be 0`, `must be greater than -9223372036854775808`, `must be a finite number, NAN|INF provided`, `must be greater than 0 for increasing ranges`, and `must be less than the range spanned by argument #1 ($start) and argument #2 ($end)`. Each bound is then classified: a one-byte NUMERIC string is ambiguous and is read as a character only when the other bound is also a string, so `range("1", "3")` yields strings while `range("1.5", "3")` yields floats. A character range walks BYTES using only the first byte of each bound (a longer bound warns `must be a single byte, subsequent bytes are ignored`), an empty string warns `must not be empty, casted to 0`, and a whole-valued float step keeps an int range int. A span too large for a hash table raises `The supplied range exceeds the maximum array size by N elements: …`.

echo implode(",", range(1, 4)), " ", implode("", range("a", "c"));   // => 1,2,3,4 abc

# array_merge

array_merge(array ...$arrays): array

Concatenates the arrays. Integer keys are renumbered from 0 and string keys are overwritten by later arrays.

echo implode(",", array_merge([1], [2, 3]));   // => 1,2,3

# array_map

array_map(?callable $callback, array $array, array ...$arrays): array

Applies the callback to each element and returns the results. With several arrays it walks them in parallel, and a null callback zips them into tuples.

echo implode(",", array_map("strtoupper", ["a", "b"]));   // => A,B

# array_filter

array_filter(array $array, ?callable $callback = null, int $mode = 0): array

Keeps the elements for which the callback is truthy, PRESERVING keys. With no callback it keeps the truthy values. `$mode` selects what the callback receives: the value (0), the value and the key (`ARRAY_FILTER_USE_BOTH`), or the key alone (`ARRAY_FILTER_USE_KEY`).

echo implode(",", array_filter([0, 1, 2]));   // => 1,2

# array_reduce

array_reduce(array $array, callable $callback, mixed $initial = null): mixed

Folds the array to a single value, calling `$callback($carry, $item)` for each element.

echo array_reduce([1, 2, 3], fn($c, $x) => $c + $x, 0);   // => 6

# array_slice

array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array

Extracts a run of elements. A negative offset counts from the end and a negative length stops that many elements from the end.

echo implode(",", array_slice([1, 2, 3, 4], 1, 2));   // => 2,3

# array_reverse

array_reverse(array $array, bool $preserve_keys = false): array

A new array with the elements in reverse order. String keys are always preserved; integer keys are renumbered unless `$preserve_keys` is truthy.

echo implode(",", array_reverse([1, 2, 3]));   // => 3,2,1

# array_sum

array_sum(array $array): int|float

Sum of the values as numbers. The result is an integer while every addend is one, and a float as soon as any is. An entry the `+` operator would reject warns `array_sum(): Addition is not supported on type <type>`; an array or an object with no numeric cast then contributes nothing, while a non-numeric string keeps the pre-8 behaviour of counting as 0.

var_dump(array_sum([1, 2.5]));   // => float(3.5)

# array_product

array_product(array $array): int|float

Product of the values as numbers, following the same integer-until-a-float rule as `array_sum`, and the same `Multiplication is not supported on type <type>` warning for an entry `*` would reject — which is why `array_product([2, "a"])` is 0, the non-numeric string counting as a factor of 0. An empty array yields 1.

echo array_product([2, 3, 4]);   // => 24

# array_flip

array_flip(array $array): array

Swaps keys and values. A later duplicate value overwrites the entry the earlier one produced.

echo array_flip(["a", "b"])["a"];   // => 0

# array_unique

array_unique(array $array, int $flags = SORT_STRING): array

Keeps the first occurrence of each distinct value, preserving keys. `SORT_STRING` (the default) compares string forms; any other `$flags` sorts under that comparison and drops each element equal to the last one kept, as the reference does.

echo implode(",", array_unique([1, 1, 2]));   // => 1,2

# array_key_exists

array_key_exists(mixed $key, array $array): bool

True when the key is present, even if its value is null — the difference from `isset()`.

var_dump(array_key_exists("a", ["a" => null]), isset(["a" => null]["a"]));   // => bool(true) bool(false)

# key_exists

key_exists(mixed $key, array $array): bool

The alias of `array_key_exists`, sharing its match arm.

# array_search

array_search(mixed $needle, array $haystack, bool $strict = false): mixed

The key of the first matching value, or `false` when none matches. `$strict` selects `===` over loose comparison.

echo array_search(2, [1, 2, 3]);   // => 1

# sort

sort(array $array): bool

Sorts ascending in place and reindexes the keys from 0. The `$flags` argument selects the comparison (`SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_NATURAL`, optionally `|SORT_FLAG_CASE`). The sort is stable, as PHP 8's is.

$a = [3, 1, 2]; sort($a); echo implode(",", $a);   // => 1,2,3

# rsort

rsort(array $array): bool

Sorts descending in place and reindexes the keys from 0.

$a = [1, 3, 2]; rsort($a); echo implode(",", $a);   // => 3,2,1

# asort

asort(array $array): bool

Sorts by value ascending while preserving the key association.

$a = ["b" => 2, "a" => 1]; asort($a); echo implode(",", array_keys($a));   // => a,b

# arsort

arsort(array $array): bool

Sorts by value descending while preserving the key association.

$a = ["a" => 1, "b" => 2]; arsort($a); echo implode(",", array_keys($a));   // => b,a

# ksort

ksort(array $array): bool

Sorts by key ascending, keeping each key with its value.

$a = ["b" => 1, "a" => 2]; ksort($a); echo implode(",", array_keys($a));   // => a,b

# krsort

krsort(array $array): bool

Sorts by key descending.

$a = ["a" => 1, "b" => 2]; krsort($a); echo implode(",", array_keys($a));   // => b,a

# array_fill

array_fill(int $start_index, int $count, mixed $value): array

An array of `$count` copies of the value, keyed from `$start_index` upward. A negative `$count` raises `ValueError: array_fill(): Argument #2 ($count) must be greater than or equal to 0` and one past `INT_MAX` raises `… is too large`; a `$start_index` high enough that the last key would pass `PHP_INT_MAX` raises `Error: Cannot add element to the array as the next element is already occupied`, before any element is written.

echo implode(",", array_fill(0, 3, "x"));   // => x,x,x

# array_combine

array_combine(array $keys, array $values): array

Pairs one array's values as keys with another's as values. Mismatched lengths throw `ValueError: array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements`.

echo array_combine(["a"], [1])["a"];   // => 1

# array_diff

array_diff(array $array, array ...$excludes): array

The entries of the first array whose VALUE (compared by string form) appears in none of the others. Keys are preserved.

echo implode(",", array_diff([1, 2, 3], [2]));   // => 1,3

# array_intersect

array_intersect(array $array, array ...$others): array

The entries of the first array whose value appears in every other array, compared by string form. Keys are preserved.

echo implode(",", array_intersect([1, 2, 3], [2, 3, 4]));   // => 2,3

# implode

implode(string $separator, array $array): string
implode(array $array): string

Joins the array's values into a string. Passing only the array joins with no separator.

echo implode(",", [1, 2, 3]);   // => 1,2,3

# join

join(string $separator, array $array): string

The alias of `implode`, sharing its match arm.

# explode

explode(string $separator, string $string): array

Splits the string on every occurrence of the separator. A positive `$limit` caps the number of parts with the last holding the remainder, a negative one drops that many parts off the end, and `0` behaves as `1`. An empty separator returns a single-element array rather than raising `ValueError`.

echo explode(",", "a,b")[1];   // => b

Core library — math

# abs

abs(int|float $num): int|float

Absolute value, preserving the operand's numeric type.

echo abs(-5);   // => 5

# floor

floor(int|float $num): float

The largest integral value not greater than the operand, returned as a float.

echo floor(3.7);   // => 3

# ceil

ceil(int|float $num): float

The smallest integral value not less than the operand, returned as a float.

echo ceil(3.2);   // => 4

# round

round(int|float $num, int $precision = 0): float

Rounds to `$precision` decimal places, halves away from zero unless the PHP 8.4 `$mode` selects another rule; all four `PHP_ROUND_HALF_*` constants are honoured.

echo round(3.14159, 2);   // => 3.14

# sqrt

sqrt(int|float $num): float

The non-negative square root. A negative operand yields NAN.

echo sqrt(16);   // => 4

# pow

pow(int|float $base, int|float $exp): int|float

The base raised to the exponent. Two integers with a non-negative exponent give an integer result; anything else gives a float.

echo pow(2, 10);   // => 1024

# intdiv

intdiv(int $num1, int $num2): int

Integer division truncated toward zero. A zero divisor throws a catchable `DivisionByZeroError` with the message `Division by zero`.

echo intdiv(7, 2);   // => 3

# fmod

fmod(float $num1, float $num2): float

The floating-point remainder of the division, keeping the sign of the dividend.

echo fmod(7.5, 2);   // => 1.5

# sin

sin(float $num): float

Sine of an angle in radians.

echo sin(0);   // => 0

# cos

cos(float $num): float

Cosine of an angle in radians.

echo cos(0);   // => 1

# tan

tan(float $num): float

Tangent of an angle in radians.

echo tan(0);   // => 0

# exp

exp(float $num): float

e raised to the given power.

echo exp(0);   // => 1

# log

log(float $num, ?float $base = M_E): float

The natural logarithm, or the logarithm in `$base` when a second argument is supplied.

echo log(8, 2);   // => 3

# log10

log10(float $num): float

The base-10 logarithm.

echo log10(1000);   // => 3

# pi

pi(): float

Returns pi, the same value as the `M_PI` constant.

echo round(pi(), 2);   // => 3.14

# max

max(mixed ...$values): mixed
max(array $values): mixed

The largest argument, or the largest element when a single array is passed. Comparison follows PHP's loose ordering rules.

echo max(3, 1, 2);   // => 3

# min

min(mixed ...$values): mixed
min(array $values): mixed

The smallest argument, or the smallest element of a single array argument.

echo min(3, 1, 2);   // => 1

Core library — types and output

# settype

settype(mixed &$var, string $type): bool

Converts `$var` in place to `$type` and returns true. Accepts `bool`/`boolean`, `int`/`integer`, `float`/`double`, `string`, `array`, `object` and `null`; the conversion is the one the matching cast performs, so a non-numeric string becomes `0` and a scalar becomes a one-element array. Any other type name is a `ValueError`.

$n = "12abc"; settype($n, "integer"); var_dump($n);   // => int(12)

# gettype

gettype(mixed $value): string

The legacy type name: `boolean`, `integer`, `double`, `string`, `array`, `object`, `NULL`, or `unknown type`. Use `get_debug_type()` for the modern short names.

echo gettype(1.0), "|", gettype(null);   // => double|NULL

# is_array

is_array(mixed $value): bool

True when the value is an array. Arrays and objects share one handle representation, so this asks the host which kind the handle points at.

var_dump(is_array([1]));   // => bool(true)

# is_int

is_int(mixed $value): bool

True only for a real integer — a numeric string is not one.

var_dump(is_int(5), is_int("5"));   // => bool(true) bool(false)

# is_integer

is_integer(mixed $value): bool

The alias of `is_int`, sharing its match arm.

# is_long

is_long(mixed $value): bool

The second alias of `is_int`, sharing the same arm.

# is_float

is_float(mixed $value): bool

True only for a real float value.

var_dump(is_float(1.5));   // => bool(true)

# is_double

is_double(mixed $value): bool

The alias of `is_float`, sharing its match arm.

# is_string

is_string(mixed $value): bool

True only for a string value.

var_dump(is_string("x"));   // => bool(true)

# is_bool

is_bool(mixed $value): bool

True only for `true` or `false`.

var_dump(is_bool(true), is_bool(1));   // => bool(true) bool(false)

# is_null

is_null(mixed $value): bool

True for null, which is also what an unset variable and a missing array key read as.

var_dump(is_null(null));   // => bool(true)

# is_numeric

is_numeric(mixed $value): bool

True for an integer, a float, or a string that parses as a number — including leading whitespace, a sign, hex-free decimals, and exponent notation.

var_dump(is_numeric("3.5"), is_numeric("3.5px"));   // => bool(true) bool(false)

# is_callable

is_callable(mixed $value): bool

True for a closure handle, and for ANY non-empty string. DIVERGENCE: the host exposes no function-table lookup here, so `is_callable("no_such_function")` is true — the name is never resolved.

var_dump(is_callable("strlen"), is_callable("nope"));   // => bool(true) bool(true)

# intval

intval(mixed $value): int

The integer value, taking the leading numeric prefix of a string and yielding 0 when there is none. DIVERGENCE: the `$base` argument is not read, so `intval("ff", 16)` is 0.

echo intval("42px");   // => 42

# floatval

floatval(mixed $value): float

The float value, taking the leading numeric prefix of a string.

echo floatval("3.5kg");   // => 3.5

# doubleval

doubleval(mixed $value): float

The alias of `floatval`, sharing its match arm.

# strval

strval(mixed $value): string

The string value. An object calls its `__toString`; one without it throws `Error`.

echo strval(42);   // => 42

# __cast_array

__cast_array(mixed $value): array

Internal target of the `(array)` cast — not a PHP function, and not meant to be called by name. An array passes through, `null` becomes the empty array, an object yields its properties keyed by name, and any other scalar becomes a one-element list. DIVERGENCE: PHP mangles private/protected property names in an object cast (`\0Class\0prop`, `\0*\0prop`); this returns the plain names.

var_dump((array)"a");   // => array(1) { [0]=> string(1) "a" }

# __cast_object

__cast_object(mixed $value): object

Internal target of the `(object)` cast — not a PHP function, and not meant to be called by name. An array becomes a `stdClass` whose keys are properties, `null` an empty `stdClass`, and any other scalar a `stdClass` with the value in a `scalar` property. An object passes through unchanged.

$o = (object)["a" => 1]; echo $o->a;   // => 1

# boolval

boolval(mixed $value): bool

The boolean value. Falsey values are `0`, `0.0`, `""`, `"0"`, the empty array, and null.

var_dump(boolval(""), boolval("0"), boolval("a"));   // => bool(false) bool(false) bool(true)

# print_r

print_r(mixed $value, bool $return = false): string|true

Renders a value in PHP's indented human-readable form. With `$return` truthy the text is returned instead of printed. A structure that contains itself prints its head and then ` *RECURSION*` in place of the repeated block.

echo print_r([1, 2], true);   // => Array\n(\n    [0] => 1\n    [1] => 2\n)

# var_dump

var_dump(mixed ...$values): void

Prints each value with its type and structure — `bool(true)`, `int(3)`, `float(1.5)`, `string(3) "abc"`, and nested `array(n) { … }`. A repeated element in a self-referential structure is replaced entirely by `*RECURSION*`, type header included.

var_dump(true);   // => bool(true)

# var_export

var_export(mixed $value, bool $return = false): string|null

Renders a value as parsable PHP source. With `$return` truthy the text is returned; otherwise it is printed and null is returned. A circular reference raises `Warning: var_export does not handle circular references` and writes `NULL` in that position, so the output stays parsable but no longer rebuilds the original.

var_export(1);   // => 1

# printf

printf(string $format, mixed ...$values): int

Writes a `sprintf`-formatted string to output and returns its length in BYTES.

printf("%d", 7);   // => 7

# json_encode

json_encode(mixed $value): string

Encodes a value as JSON, escaping `/` and non-ASCII characters by default and returning `false` (with `json_last_error()` set) for a NAN or INF (`JSON_ERROR_INF_OR_NAN`), a structure containing itself (`JSON_ERROR_RECURSION`), a resource (`JSON_ERROR_UNSUPPORTED_TYPE`) or a pure enum case (`JSON_ERROR_NON_BACKED_ENUM`). `JSON_PRETTY_PRINT`, `JSON_UNESCAPED_SLASHES`, `JSON_UNESCAPED_UNICODE`, `JSON_UNESCAPED_LINE_TERMINATORS`, `JSON_PRESERVE_ZERO_FRACTION`, `JSON_PARTIAL_OUTPUT_ON_ERROR` and `JSON_THROW_ON_ERROR` are honoured. DIVERGENCE: the `$depth` argument is not read. `json_decode` lives in the `json` module, not here.

echo json_encode([1, 2, 3]);   // => [1,2,3]

Strings

# substr_count

substr_count(string $haystack, string $needle, int $offset = 0, ?int $length = null): int

Counts non-overlapping matches inside the byte window `[$offset, $offset + $length)`. Negative offsets and lengths count from the end. A window that leaves the haystack is refused rather than clamped: `ValueError: substr_count(): Argument #3 ($offset)` (or `#4 ($length)`) `must be contained in argument #1 ($haystack)`. An empty needle throws `ValueError: substr_count(): Argument #2 ($needle) must not be empty`. The window is a raw byte slice, so a multibyte haystack can be cut mid-character.

echo substr_count("aaa", "aa");   // => 1

# substr_replace

substr_replace(array|string $string, array|string $replace, array|int $offset, array|int|null $length = null): string|array

Splices the replacement over the byte range starting at `$offset`. An array `$string` returns an array spliced element-wise, with `$replace`, `$offset` and `$length` consumed positionally and falling back to `""` / `0` / to-the-end once exhausted. The result is rebuilt lossily, so splicing at a non-character boundary yields U+FFFD.

echo substr_replace("Hello", "XY", 1, 3);   // => HXYo

# addcslashes

addcslashes(string $string, string $characters): string

Backslash-escapes every byte listed in `$characters`, which may use `a..z` inclusive ranges. Outside printable ASCII the escape is the C mnemonic (`\n`, `\t`, `\r`, `\a`, `\v`, `\b`, `\f`) or a three-digit octal. A malformed range warns `addcslashes(): Invalid '..'-range, …` and contributes nothing.

echo addcslashes("foo[bar]", "A..z");   // => \f\o\o\[\b\a\r\]

# stripcslashes

stripcslashes(string $string): string

The inverse of `addcslashes`: understands the C mnemonics plus `\xHH` (one or two hex digits) and `\NNN` (up to three octal digits). An unrecognized escape yields the escaped character itself, so `\z` is `z`.

echo stripcslashes('\101\x42');   // => AB

# count_chars

count_chars(string $string, int $mode = 0): array|string

Per-byte histogram. Mode 0 reports all 256 counters, 1 only the non-zero ones, 2 only the zero ones; modes 3 and 4 return a STRING of the bytes that did / did not occur. A `$mode` outside 0-4 throws `ValueError`.

print_r(count_chars("aab", 3));   // => ab

# strtok

strtok(string $string, ?string $token = null): string|false

Stateful tokenizer. Two arguments install a new subject and answer its first token; one argument continues the saved subject with a (possibly different) delimiter set. Running out of tokens answers `false` AND discards the subject, so a further one-argument call keeps answering `false` rather than restarting.

echo strtok("a b", " "), strtok(" ");   // => ab

# strtr

strtr(string $string, array $pairs): string
strtr(string $string, string $from, string $to): string

Two-argument form: longest-key-first, non-overlapping substring replacement in a single left-to-right pass, dropping empty keys. Three-argument form: byte-wise translation with both sets truncated to the shorter length. DIVERGENCE: in the two-argument form an unmatched byte at or above 0x80 is re-encoded as its Latin-1 codepoint, so untouched non-ASCII text is mangled.

echo strtr("hi all", ["hi" => "bye"]);   // => bye all

# strstr

strstr(string $haystack, string $needle, bool $before_needle = false): string|false

The part of the haystack from the first match onward, or the part before it when `$before_needle` is truthy; `false` when absent. An empty needle matches at offset 0 (PHP 8 semantics).

echo strstr("user@example.com", "@");   // => @example.com

# strchr

strchr(string $haystack, string $needle, bool $before_needle = false): string|false

The alias of `strstr`, sharing its match arm — the same alias relationship PHP has.

# stristr

stristr(string $haystack, string $needle, bool $before_needle = false): string|false

Case-insensitive `strstr`. DIVERGENCE: the folding is ASCII-only, so non-ASCII letters never match case-insensitively.

echo stristr("HELLO", "ell");   // => ELLO

# strrchr

strrchr(string $haystack, string $needle): string|false

The substring from the LAST occurrence of the needle's FIRST BYTE through the end; `false` when absent or the needle is empty. DIVERGENCE: PHP 8.3's `$before_needle` parameter is not read.

echo strrchr("a/b/c", "/");   // => /c

# str_increment

str_increment(string $string): string

Perl-style alphanumeric increment (PHP 8.3): each position steps within `a-z`, `A-Z` or `0-9` and carries left on wrap-around; a carry out of the first position prepends `1` for a digit or the wrapped letter otherwise. An empty or non-alphanumeric-ASCII string is a `ValueError`.

var_dump(str_increment("Az"));   // => string(2) "Ba"

# str_decrement

str_decrement(string $string): string

Inverse of `str_increment` (PHP 8.3): borrows leftwards, and drops the first position when it borrows out of it or leaves a leading `0`. A string starting with `0`, or a single `a`/`A`, is out of decrement range (`ValueError`), as are empty and non-alphanumeric-ASCII strings.

var_dump(str_decrement("Ba"));   // => string(2) "Az"

# strpbrk

strpbrk(string $string, string $characters): string|false

The substring beginning at the first byte that belongs to the character set, through the end; `false` when no byte matches.

echo strpbrk("This is a test", "st");   // => s is a test

# strspn

strspn(string $string, string $characters, int $offset = 0, ?int $length = null): int

Length in bytes of the initial run within the window whose bytes all belong to the set. Set membership is byte-oriented, so a multibyte mask character is matched byte by byte.

echo strspn("42 apples", "0123456789");   // => 2

# strcspn

strcspn(string $string, string $characters, int $offset = 0, ?int $length = null): int

The complement of `strspn`: the length of the initial run of bytes NOT in the set. It shares the same match arm with the membership test inverted.

echo strcspn("abc123", "0123456789");   // => 3

# stripos

stripos(string $haystack, string $needle, int $offset = 0): int|false

Byte offset of the first ASCII-case-insensitive match at or after the offset, or `false`. A negative offset counts from the end and an empty needle returns the offset. DIVERGENCE: folding is ASCII-only.

echo stripos("Hello", "L");   // => 2

# strrpos

strrpos(string $haystack, string $needle, int $offset = 0): int|false

Byte offset of the LAST match. A non-negative offset requires the match to start at or after it; a negative one caps how late it may start. An empty needle returns the string length (PHP 8 semantics).

echo strrpos("hello", "l");   // => 3

# strripos

strripos(string $haystack, string $needle, int $offset = 0): int|false

`strrpos` with ASCII case-insensitive comparison; it shares the same match arm. DIVERGENCE: folding is ASCII-only.

echo strripos("HELLO", "l");   // => 3

# strncasecmp

strncasecmp(string $string1, string $string2, int $length): int

Compares the first `$length` bytes after ASCII-lowercasing, returning `-1`, `0`, or `1`. A negative length raises `strncasecmp(): Argument #3 ($length) must be greater than or equal to 0`.

echo strncasecmp("Hello", "HELLO world", 5);   // => 0

# str_ireplace

str_ireplace(array|string $search, array|string $replace, string|array $subject, &$count = null): string|array

ASCII-case-insensitive `str_replace`. An array `$search` is applied in sequence, index-matched against an array `$replace` (missing entries become `""`) or with one scalar for all. An array `$subject` is processed element-wise with its keys kept, and the by-reference `$count` receives the number of replacements.

echo str_ireplace("WORLD", "there", "Hello world");   // => Hello there

# nl2br

nl2br(string $string): string

Inserts a `<br />` before each `\r\n`, `\n\r`, `\r`, or `\n`, keeping the original break. DIVERGENCE: the `$use_xhtml` argument is not read, so the output is always the XHTML `<br />`.

echo nl2br("a\nb");   // => a<br />\nb

# chunk_split

chunk_split(string $string, int $length = 76, string $separator = "\r\n"): string

Appends the separator after every `$length` bytes. A non-positive length throws `ValueError: chunk_split(): Argument #2 ($length) must be greater than 0`.

echo chunk_split("abcdef", 2, "-");   // => ab-cd-ef-

# quotemeta

quotemeta(string $string): string

Backslash-escapes each of `. \ + * ? [ ^ ] $ ( )`. The escape set is ASCII, so the result matches PHP's byte behaviour.

echo quotemeta("1+1=2");   // => 1\+1=2

# addslashes

addslashes(string $string): string

Backslash-escapes `'`, `"`, and `\`, and maps a NUL byte to the two-character sequence `\0`.

echo addslashes("O'Reilly");   // => O\'Reilly

# stripslashes

stripslashes(string $string): string

Removes one level of backslashes, keeping the escaped character — except `\0`, which becomes a real NUL. A trailing lone backslash is dropped.

echo stripslashes("O\\'Reilly");   // => O'Reilly

# str_rot13

str_rot13(string $string): string

Rotates ASCII letters by 13 places. Every other character, including all non-ASCII, passes through untouched. Applying it twice restores the input.

echo str_rot13("abc");   // => nop

# similar_text

similar_text(string $string1, string $string2): int

The number of matching characters, using PHP's own recursive longest-common-substring algorithm. DIVERGENCE: the by-reference `$percent` out-parameter does not exist, so only the count is available.

echo similar_text("World", "word");   // => 3

# levenshtein

levenshtein(string $string1, string $string2, int $insertion_cost = 1, int $replacement_cost = 1, int $deletion_cost = 1): int

Weighted edit distance over BYTES, so a multibyte character counts as several edits. Note the cost defaults apply only when the argument is absent — passing an explicit null coerces that cost to 0.

echo levenshtein("kitten", "sitting");   // => 3

# vsprintf

vsprintf(string $format, array $values): string

`sprintf` with the arguments supplied as one array, spread in iteration order with keys discarded.

echo vsprintf("%d-%s", [1, "x"]);   // => 1-x

# vprintf

vprintf(string $format, array $values): int

Writes a `vsprintf` result to output and returns its length in BYTES.

vprintf("%d", [7]);   // => 7

# sscanf

sscanf(string $string, string $format, mixed &...$vars): array|int|null

Parses the string against the format. With two arguments the result is an array of the converted values, padded with nulls to one entry per non-suppressed specifier; with by-reference arguments it is the number of specifiers processed, and a variable no conversion reached is left untouched. Supports `%d %D %i %o %x %X %u %f %e %E %g %s %c %n %[…] %%`, `*` suppression, field widths, the ignored `l`/`L`/`h` size modifiers, literal text and whitespace runs. When the input runs out before any conversion the answer is `null` (two-argument) or `-1` (by-reference). DIVERGENCE: the `%n$` positional form is not implemented, and no format is rejected up front the way PHP's `ValidateFormat` does.

print_r(sscanf("age:42", "age:%d"));   // => Array\n(\n    [0] => 42\n)

# htmlspecialchars_decode

htmlspecialchars_decode(string $string): string

Decodes only what `htmlspecialchars` can produce — `&lt;`, `&gt;`, `&amp;`, `&quot;` and the numeric single quote — and `$flags` gates the two quote entities. A named entity like `&eacute;` and any other numeric reference are left standing, which is what separates it from `html_entity_decode`.

echo htmlspecialchars_decode("a&lt;b");   // => a<b

# html_entity_decode

html_entity_decode(string $string): string

Decodes the full HTML 4.01 named-entity table plus decimal (`&#233;`) and hexadecimal (`&#xE9;`) references; an unknown entity, and an `&` with no terminating `;`, are copied through verbatim. `$flags` gates the quote entities. DIVERGENCE: `$encoding` is not read (input is treated as UTF-8).

echo html_entity_decode("caf&eacute;");   // => café

# strip_tags

strip_tags(string $string): string

A port of `php_strip_tags_ex`, so its five-state scanner — HTML tag, `<? … ?>`, `<! … >`, `<!-- … -->`, and the `<?xml` / `<!DOCTYPE` re-entries — matches the reference on quoted attributes containing `>`, nested `<`, and unterminated tags. `$allowed_tags` is honoured in both spellings, the string `"<b><i>"` and the array `["b", "i"]`; an allowed tag is re-emitted verbatim, attributes included.

echo strip_tags("<p>hi</p>");   // => hi

# escapeshellarg

escapeshellarg(string $arg): string

A port of `php_escape_shell_arg` (POSIX): the argument single-quoted, each `'` written `'\''`. Bytes are walked as `php_mblen` reads them in a UTF-8 locale — a multibyte character is copied whole, a byte that begins none is dropped, and a character cut off at the end of the argument is carried into the next escape call, as the reference's persistent `mbstate_t` carries it. A NUL byte is a `ValueError`.

echo escapeshellarg("it's");   // => 'it'\''s'

# escapeshellcmd

escapeshellcmd(string $command): string

A port of `php_escape_shell_cmd` (POSIX): each of ``#&;`|*?~<>^()[]{}$\`` and newline gets a backslash; a quote does not when a matching quote follows it, and a later quote of the same kind closes that pair. Multibyte handling and the NUL refusal are `escapeshellarg`'s.

echo escapeshellcmd("ls; rm");   // => ls\; rm

# mb_strlen

mb_strlen(string $string): int

The number of Unicode CODEPOINTS, the multibyte counterpart of `strlen`. The `$encoding` argument is accepted and ignored — phplang strings are always UTF-8.

echo mb_strlen("héllo");   // => 5

# mb_strtoupper

mb_strtoupper(string $string): string

Full Unicode uppercase, which can change the string's length (German sharp s becomes `SS`). The `$encoding` argument is ignored.

echo mb_strtoupper("héllo");   // => HÉLLO

# mb_strtolower

mb_strtolower(string $string): string

Full Unicode lowercase. The `$encoding` argument is ignored.

echo mb_strtolower("HÉLLO");   // => héllo

# mb_substr

mb_substr(string $string, int $start, ?int $length = null): string

Codepoint-aware substring. A negative start counts from the end, a negative length omits that many trailing codepoints, and the end is clamped. The `$encoding` argument is ignored.

echo mb_substr("héllo", 1, 3);   // => éll

Multibyte strings

# mb_str_split

mb_str_split(string $string, int $length = 1): array

Splits into chunks of `$length` CODEPOINTS; the final chunk may be shorter. A length below 1 throws `ValueError: mb_str_split(): Argument #2 ($length) must be greater than 0`.

echo mb_str_split("héllo")[1];   // => é

# mb_convert_case

mb_convert_case(string $string, int $mode): string

Mode 1 lowercases, mode 2 title-cases, and mode 0 — plus every UNRECOGNIZED mode — uppercases. Title-casing uppercases the first letter of each WORD and lowercases the rest of it; a Unicode case-ignorable character (an apostrophe, `.`, `:`) is transparent rather than a word break, so `"who's who"` becomes `"Who's Who"` while `"x,y"` becomes `"X,Y"`. DIVERGENCE: PHP's `MB_CASE_*_SIMPLE` modes (3-5) are not distinguished.

echo mb_convert_case("hello world", MB_CASE_TITLE);   // => Hello World

# mb_strpos

mb_strpos(string $haystack, string $needle, int $offset = 0): int|false

The CODEPOINT index of the first match at or after the offset, or `false`. An offset outside `[-len, len]` raises `mb_strpos(): Argument #3 ($offset) must be contained in argument #1 ($haystack)`.

echo mb_strpos("héllo", "llo");   // => 2

# mb_stripos

mb_stripos(string $haystack, string $needle, int $offset = 0): int|false

Case-insensitive `mb_strpos`. DIVERGENCE: folding keeps only the first codepoint of each character's lowercase expansion so that indexes stay 1:1, which differs from PHP's full case mapping for characters like U+0130.

echo mb_stripos("HÉLLO", "é");   // => 1

# mb_strrpos

mb_strrpos(string $haystack, string $needle, int $offset = 0): int|false

The codepoint index of the LAST match, with the same offset rules and out-of-range error as `mb_strpos`. An empty needle returns the codepoint length.

echo mb_strrpos("héllo", "l");   // => 3

# mb_strripos

mb_strripos(string $haystack, string $needle, int $offset = 0): int|false

Case-insensitive `mb_strrpos`, using the same single-codepoint folding as `mb_stripos`.

# mb_substr_count

mb_substr_count(string $haystack, string $needle): int

Non-overlapping match count in codepoints. An empty needle throws `ValueError: mb_substr_count(): Argument #2 ($needle) must not be empty`.

echo mb_substr_count("ababa", "aba");   // => 1

# mb_str_pad

mb_str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string

Pads to `$length` CODEPOINTS by cycling the pad string. All three `STR_PAD_*` modes are honoured, with `STR_PAD_BOTH` flooring the left side. An empty pad string throws `ValueError: mb_str_pad(): Argument #3 ($pad_string) must not be empty`, and only when padding is actually needed.

echo mb_str_pad("é", 3, "-");   // => é--

# mb_trim

mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string

Strips NUL and the Unicode `White_Space` code points (plus U+180E) from both ends, or every code point of `$characters`, which is a SET: there is no `a..z` range form as in `trim()`. An unknown `$encoding` throws `ValueError`.

echo mb_trim("\u{3000}héllo\u{a0}");   // => héllo

# mb_ltrim

mb_ltrim(string $string, ?string $characters = null, ?string $encoding = null): string

`mb_trim()` applied to the start of the string only.

echo mb_ltrim("xxhixx", "x");   // => hixx

# mb_rtrim

mb_rtrim(string $string, ?string $characters = null, ?string $encoding = null): string

`mb_trim()` applied to the end of the string only.

echo mb_rtrim("xxhixx", "x");   // => xxhi

# mb_strstr

mb_strstr(string $haystack, string $needle, bool $before_needle = false, ?string $encoding = null): string|false

The part of the haystack from the first occurrence of the whole needle (or the part before it), compared by code point; `false` when absent. An empty needle matches at the start.

echo mb_strstr("héllo wörld", "wö");   // => wörld

# mb_stristr

mb_stristr(string $haystack, string $needle, bool $before_needle = false, ?string $encoding = null): string|false

`mb_strstr()` with a case-insensitive comparison; the returned text keeps the haystack's own case.

echo mb_stristr("héLLo", "ll");   // => LLo

# mb_strrchr

mb_strrchr(string $haystack, string $needle, bool $before_needle = false, ?string $encoding = null): string|false

`mb_strstr()` for the LAST occurrence of the needle.

echo mb_strrchr("a/b/c", "/");   // => /c

# mb_strrichr

mb_strrichr(string $haystack, string $needle, bool $before_needle = false, ?string $encoding = null): string|false

`mb_strrchr()` with a case-insensitive comparison.

echo mb_strrichr("aXbxc", "x");   // => xc

# mb_strimwidth

mb_strimwidth(string $string, int $start, int $width, string $trim_marker = "", ?string $encoding = null): string

Cuts the string from character `$start` so that it, with `$trim_marker` standing in for the removed tail, fits `$width` display columns (East Asian wide characters count 2). A negative `$start` counts columns from the end and a negative `$width` is relative to the string's width; either out of range throws `ValueError`.

echo mb_strimwidth("Hello World", 0, 10, "...");   // => Hello W...

# mb_encode_numericentity

mb_encode_numericentity(string $string, array $map, ?string $encoding = null, bool $hex = false): string

Replaces each code point inside a `[start, end, offset, mask]` range of `$map` with `&#N;` (`&#xH;` when `$hex`), `N` being `(code point + offset) & mask`. A map whose length is not a multiple of four throws `ValueError`.

echo mb_encode_numericentity("é", [0x80, 0x10ffff, 0, 0xffffff]);   // => &#233;

# mb_decode_numericentity

mb_decode_numericentity(string $string, array $map, ?string $encoding = null): string

The inverse of `mb_encode_numericentity()`: a decimal or lowercase-`x` hexadecimal entity whose value minus the offset lies in a range becomes that character. An entity outside every range, or an uppercase `&#X`, is left as written.

echo mb_decode_numericentity("&#233;", [0x80, 0x10ffff, 0, 0xffffff]);   // => é

# mb_ord

mb_ord(string $string): int|false

The Unicode codepoint of the first character, or `false` for an empty string — the multibyte counterpart of `ord`, which reports a byte instead.

echo mb_ord("é");   // => 233

# mb_chr

mb_chr(int $codepoint): string|false

The character for a codepoint, or `false` when it is negative, a surrogate, or above U+10FFFF.

echo mb_chr(233);   // => é

# mb_lcfirst

mb_lcfirst(string $string): string

Lowercases the first character with full Unicode folding and leaves the remainder untouched; the empty string maps to itself.

echo mb_lcfirst("École");   // => école

# mb_ucfirst

mb_ucfirst(string $string): string

Uppercases the first character with full Unicode folding, which may expand it to several codepoints.

echo mb_ucfirst("école");   // => École

# mb_scrub

mb_scrub(string $string): string

Returns the string verbatim. It is a genuine no-op here: a phplang string is always valid UTF-8, so there is never an ill-formed sequence to substitute.

# mb_strcut

mb_strcut(string $string, int $start, ?int $length = null): string

A BYTE-offset substring that never splits a character: the offsets count bytes, then both endpoints are floored to the nearest UTF-8 boundary.

echo mb_strcut("héllo", 0, 2);   // => h

# mb_split

mb_split(string $pattern, string $string, int $limit = -1): array|false

Splits on a regular expression. A positive limit caps the piece count with the last piece holding the remainder. DIVERGENCE: the Rust `regex` crate replaces Oniguruma, so backreferences and lookaround are unsupported and an uncompilable pattern returns `false`.

print_r(mb_split("[,;]", "a,b;c"));   // => Array\n(\n    [0] => a\n    [1] => b\n    [2] => c\n)

# mb_convert_kana

mb_convert_kana(string $string, string $mode = "KV"): string

Converts between fullwidth and halfwidth ASCII by codepoint arithmetic: `a`/`r`/`n` fold fullwidth to halfwidth for printables, letters, and digits, `A`/`R`/`N` do the reverse, and `s`/`S` map the ideographic space. DIVERGENCE: the kana modes `k K h H c C v V` are unimplemented, which includes the DEFAULT mode `"KV"` — calling it with no mode is a no-op.

# mb_strwidth

mb_strwidth(string $string): int

The display width, counting 2 for codepoints in the 23 East-Asian wide and fullwidth ranges ported from PHP's own table and 1 for everything else. DIVERGENCE: combining marks and zero-width characters count as 1, not 0.

echo mb_strwidth("ab");   // => 2

# mb_convert_encoding

mb_convert_encoding(array|string $string, string $to_encoding, array|string|null $from_encoding = null): array|string|false

Converts between `UTF-8`, `ASCII` and `ISO-8859-1`/`Latin-1`, writing `?` for a character the target cannot hold and for each maximal invalid subpart of the input. `$from_encoding` is one charset, or a candidate list (array or comma-separated) of which the first the bytes are valid in is used. Any OTHER target raises `ValueError: mb_convert_encoding(): Argument #2 ($to_encoding) must be a valid encoding, "…" given`. DIVERGENCE: only those three charsets convert — another source charset is read as UTF-8 — and an array `$string` is unsupported.

echo mb_convert_encoding("héllo", "ASCII");   // => h?llo

# mb_detect_encoding

mb_detect_encoding(string $string, array|string|null $encodings = null): string|false

The first candidate the string satisfies, where `ASCII` requires every byte below 0x80 and `UTF-8` always succeeds; any other candidate never matches and an exhausted list yields `false`. The default order is ASCII then UTF-8. DIVERGENCE: `$strict` is ignored, and real detection is impossible because strings are always valid UTF-8.

echo mb_detect_encoding("abc");   // => ASCII

# mb_check_encoding

mb_check_encoding(string $value = "", ?string $encoding = null): bool

Returns true unless the encoding normalizes to `ASCII`, in which case it checks that every byte is below 0x80. DIVERGENCE: a missing `$value` checks the empty string rather than all previous output, and the array form is unsupported.

var_dump(mb_check_encoding("héllo", "ASCII"));   // => bool(false)

# mb_internal_encoding

mb_internal_encoding(?string $encoding = null): string|bool

With no argument returns the stored encoding, defaulting to `UTF-8`; with one it stores the raw string and returns true. DIVERGENCE: the name is never validated, the stored value only affects `mb_check_encoding`, and the state is thread-local and NOT reset between evaluations on the same thread.

echo mb_internal_encoding();   // => UTF-8

Text formatting

# fprintf

fprintf(resource $stream, string $format, mixed ...$values): int|false

Formats with `sprintf`, writes the bytes to the stream, flushes a dirty file resource to disk, and returns the byte count — or `false` when the write fails.

$f = fopen("/tmp/x.txt", "w"); echo fprintf($f, "%d", 42); fclose($f);   // => 2

# vfprintf

vfprintf(resource $stream, string $format, array $values): int|false

`fprintf` with the format arguments supplied as one array, spread in iteration order with keys discarded.

# fscanf

fscanf(resource $stream, string $format): array|false

Reads one line from the stream and parses it with `sscanf`. DIVERGENCE: at end of file it returns `false`, not PHP's `-1`, deliberately so that `while ($r = fscanf(…))` terminates. The by-reference extra-argument form does not exist — unlike `sscanf`, which does implement it.

# array_change_key_case

array_change_key_case(array $array, int $case = CASE_LOWER): array

A copy with every STRING key ASCII-lowercased (case 0, the default and the fallback) or ASCII-uppercased (case 1). Integer keys pass through. Folding is ASCII-only and locale-independent, matching PHP, so key length never changes.

print_r(array_change_key_case(["AbC" => 1]));   // => Array\n(\n    [abc] => 1\n)

# get_html_translation_table

get_html_translation_table(int $table = HTML_SPECIALCHARS, int $flags = ENT_QUOTES): array

The character-to-entity map: `&`, `<`, and `>` always, plus `"` and `'` per the quote bits of `$flags`. With `$table` = 1 (`HTML_ENTITIES`) it appends the 96-entry ISO-8859-1 supplement U+00A0-U+00FF. DIVERGENCE: only the Latin-1 supplement is included, the `$encoding` argument is not read, and the doctype bits are ignored so `'` is always `&#039;`.

Arrays

# array_column

array_column(array $rows, ?string $column_key, ?string $index_key = null): array

Plucks one column out of a list of rows, optionally re-keying by another column. A null column key keeps the whole row, and a row missing the column is skipped. Rows may be arrays or objects.

echo implode(",", array_column([["id" => 1], ["id" => 2]], "id"));   // => 1,2

# array_chunk

array_chunk(array $array, int $size, bool $preserve_keys = false): array

Splits into a list of sub-arrays of at most `$size` elements. A size below 1 throws `ValueError: array_chunk(): Argument #2 ($length) must be greater than 0`.

echo count(array_chunk([1, 2, 3], 2));   // => 2

# array_fill_keys

array_fill_keys(array $keys, mixed $value): array

An array using each element of `$keys` as a key, every entry set to the same value.

print_r(array_fill_keys(["a"], 0));   // => Array\n(\n    [a] => 0\n)

# array_pad

array_pad(array $array, int $size, mixed $value): array

Pads to `abs($size)` elements — a positive size pads on the right, a negative one on the left. Integer keys are renumbered and string keys preserved, as `array_merge` does.

echo implode(",", array_pad([1], 3, 0));   // => 1,0,0

# array_key_first

array_key_first(array $array): mixed

The first key in insertion order, or null for an empty array.

var_dump(array_key_first(["a" => 1, "b" => 2]));   // => string(1) "a"

# array_key_last

array_key_last(array $array): mixed

The last key in insertion order, or null for an empty array.

var_dump(array_key_last(["a" => 1, "b" => 2]));   // => string(1) "b"

# array_first

array_first(array $array): mixed

The first value in insertion order, or null for an empty array (PHP 8.5).

var_dump(array_first(["a" => 1, "b" => 2]));   // => int(1)

# array_last

array_last(array $array): mixed

The last value in insertion order, or null for an empty array (PHP 8.5).

var_dump(array_last(["a" => 1, "b" => 2]));   // => int(2)

# array_is_list

array_is_list(array $array): bool

True when the keys are exactly `0, 1, …, n-1` in order. A non-array argument returns false rather than raising a `TypeError`.

var_dump(array_is_list([1, 2]), array_is_list([1 => 1]));   // => bool(true) bool(false)

# array_diff_key

array_diff_key(array $array, array ...$excludes): array

The entries of the first array whose KEY is absent from every other array. Keys are compared by their string form.

print_r(array_diff_key(["a" => 1, "b" => 2], ["a" => 9]));   // => Array\n(\n    [b] => 2\n)

# array_intersect_key

array_intersect_key(array $array, array ...$others): array

The entries of the first array whose key is present in every other array. It shares the `array_diff_key` arm with the test inverted.

print_r(array_intersect_key(["a" => 1, "b" => 2], ["a" => 9]));   // => Array\n(\n    [a] => 1\n)

# array_diff_assoc

array_diff_assoc(array $array, array ...$excludes): array

Like `array_diff_key` but matching on key AND value, both compared by string form.

# array_intersect_assoc

array_intersect_assoc(array $array, array ...$others): array

Keeps the entries whose key-and-value pair appears in every other array, comparing both by string form.

# array_merge_recursive

array_merge_recursive(array ...$arrays): array

Merges arrays, recursing into shared STRING keys: two arrays under one key merge, and anything else under a duplicate string key is gathered into a flat list. Integer keys always append. Nested arrays are deep-copied, so the inputs are never mutated.

print_r(array_merge_recursive(["k" => "a"], ["k" => "b"]));
// => Array\n(\n    [k] => Array\n        (\n            [0] => a\n            [1] => b\n        )\n\n)

# array_replace

array_replace(array $base, array ...$rest): array

Starts from `$base`, then overwrites or inserts every entry of each later array by key. There is no recursion into nested arrays.

print_r(array_replace(["a" => 1], ["a" => 2]));   // => Array\n(\n    [a] => 2\n)

# array_replace_recursive

array_replace_recursive(array $base, array ...$rest): array

As `array_replace`, except that when both sides hold an array under the same key the two are merged recursively instead of the later one replacing the earlier wholesale. Any other type pairing, or a key present on only one side, replaces.

print_r(array_replace_recursive(["a" => ["b" => 1, "c" => 2]], ["a" => ["b" => 9]]));   // => Array\n(\n    [a] => Array\n        (\n            [b] => 9\n            [c] => 2\n        )\n\n)

# array_count_values

array_count_values(array $array): array

Tallies how often each value occurs. Only integer and string values are counted; every other value type is skipped, matching PHP.

print_r(array_count_values(["a", "a", "b"]));   // => Array\n(\n    [a] => 2\n    [b] => 1\n)

# usort

usort(array $array, callable $callback): bool

Sorts by value with a user comparator, then reindexes from 0. The sort is stable, as PHP's is, and tolerates a comparator that contradicts itself (`fn() => random_int(-1, 1)`) by answering with some permutation rather than failing. The comparator runs the VM, so an exception it throws stops the sort.

$a = [3, 1, 2]; usort($a, fn($x, $y) => $x <=> $y); echo implode(",", $a);   // => 1,2,3

# uasort

uasort(array $array, callable $callback): bool

Sorts by value with a user comparator while preserving the key association.

$a = ["b" => 2, "a" => 1]; uasort($a, fn($x, $y) => $x <=> $y);
echo implode(",", array_keys($a));   // => a,b

# uksort

uksort(array $array, callable $callback): bool

Sorts by KEY with a user comparator while preserving the key association.

$a = ["b" => 1, "a" => 2]; uksort($a, fn($x, $y) => strcmp($x, $y));
echo implode(",", array_keys($a));   // => a,b

# natsort

natsort(array $array): bool

Natural-order sort by value, preserving keys. Digit runs compare numerically, so `img12` sorts after `img2`. A run with a leading zero compares left-aligned, matching PHP's `strnatcmp`.

$a = ["img12", "img2"]; natsort($a); echo implode(",", $a);   // => img2,img12

# natcasesort

natcasesort(array $array): bool

`natsort` with case folded before comparison.

# shuffle

shuffle(array $array): bool

Randomizes the order in place and reindexes from 0, with the reference's own walk (`php_array_data_shuffle`) over the shared Mt19937 engine — so after `mt_srand($seed)` the order is the reference's.

mt_srand(3); $a = [1, 2, 3, 4, 5]; shuffle($a); echo implode(",", $a);   // => 4,3,5,1,2

# array_rand

array_rand(array $array, int $num = 1): mixed

One random key, or an array of `$num` distinct keys in their original order. An EMPTY array raises `ValueError: array_rand(): Argument #1 ($array) must not be empty` — there is no `$num` that would work — while a `$num` outside `1..count($array)` on a non-empty array names argument #2 instead. Picks with the reference's `php_array_pick_keys` over the shared Mt19937 engine, so a seeded program picks the reference's keys.

# array_walk

array_walk(array $array, callable $callback, mixed $extra = null): bool

Calls `$callback($value, $key[, $extra])` for every element and returns true. The value is passed through a reference cell, so a `function (&$v)` callback writes back into the array, scalars included.

$a = [1, 2]; array_walk($a, function ($v, $k) { echo $k . $v; });   // => 0112

# compact

compact(string|array ...$names): array

Builds an array from the named variables, pulling each bound value out of the current scope. A name may itself be an array of names, recursively. A name that is not BOUND is skipped with `Warning: compact(): Undefined variable $x` — a variable holding null is bound, so it is captured with no warning — and an argument that is neither a string nor an array is skipped with `Warning: compact(): Argument #N must be string or array of strings, <type> given`, numbered by the top-level argument even when it is nested inside an array of names.

$x = 1; $y = 2; print_r(compact("x", "y"));   // => Array\n(\n    [x] => 1\n    [y] => 2\n)

# extract

extract(array $array): int

Imports each string-keyed entry as a variable in the current scope and returns how many were set. Integer keys are skipped because they are not valid variable names. DIVERGENCE: the `$flags` and `$prefix` arguments do not exist.

extract(["n" => 7]); echo $n;   // => 7

# end

end(array $array): mixed

Moves the array's internal pointer to the last element and returns its value; `false` for an empty array. The cursor lives in a side table keyed by the array handle with an append-invariant fingerprint, so appending does not rewind it — matching PHP.

$a = [1, 2, 3]; echo end($a);   // => 3

# reset

reset(array $array): mixed

Moves the internal pointer to the first element and returns its value; `false` for an empty array.

$a = [1, 2, 3]; end($a); echo reset($a);   // => 1

# current

current(array $array): mixed

The value at the internal pointer without moving it, or `false` once the pointer has fallen off either end.

$a = [1, 2]; echo current($a);   // => 1

# pos

pos(array $array): mixed

The alias of `current`, sharing its match arm.

# key

key(array $array): mixed

The key at the internal pointer, or null once the pointer is off the end.

$a = ["a" => 1]; echo key($a);   // => a

# next

next(array $array): mixed

Advances the internal pointer and returns the new element's value, or `false` once it runs past the end. The off-the-end state is sticky, as in PHP: further `next`/`prev` calls stay invalid until `reset` or `end`.

$a = [1, 2]; echo next($a);   // => 2

# prev

prev(array $array): mixed

Steps the internal pointer back one element and returns its value, or `false` once it runs past the start, entering the same sticky invalid state.

$a = [1, 2]; end($a); echo prev($a);   // => 1

Math

# expm1

expm1(float $num): float

Computes `exp($num) - 1` with the precision-preserving `exp_m1`, which matters for arguments near zero.

echo expm1(0);   // => 0

# log1p

log1p(float $num): float

Computes `log(1 + $num)` precisely for arguments near zero.

echo log1p(0);   // => 0

# sinh

sinh(float $num): float

Hyperbolic sine.

echo sinh(0);   // => 0

# cosh

cosh(float $num): float

Hyperbolic cosine.

echo cosh(0);   // => 1

# tanh

tanh(float $num): float

Hyperbolic tangent.

echo tanh(0);   // => 0

# asinh

asinh(float $num): float

Inverse hyperbolic sine.

echo asinh(0);   // => 0

# acosh

acosh(float $num): float

Inverse hyperbolic cosine. An argument below 1 yields NAN rather than raising.

echo acosh(1);   // => 0

# atanh

atanh(float $num): float

Inverse hyperbolic tangent. An argument outside `(-1, 1)` yields NAN or an infinity rather than raising.

echo atanh(0);   // => 0

# asin

asin(float $num): float

Arc sine in radians; `|$num| > 1` yields NAN.

echo asin(0);   // => 0

# acos

acos(float $num): float

Arc cosine in radians; `|$num| > 1` yields NAN.

echo acos(1);   // => 0

# atan

atan(float $num): float

Arc tangent in radians.

echo atan(0);   // => 0

# atan2

atan2(float $y, float $x): float

The two-argument arc tangent of `$y / $x` in radians, using the signs of both operands to select the quadrant. Note the first argument is the ordinate.

echo atan2(0, 1);   // => 0

# deg2rad

deg2rad(float $num): float

Converts degrees to radians as `$num * PI / 180`.

echo deg2rad(0);   // => 0

# rad2deg

rad2deg(float $num): float

Converts radians to degrees as `$num * 180 / PI`.

echo rad2deg(0);   // => 0

# fpow

fpow(float $num, float $exponent): float

IEEE 754 `pow` on two floats: no integer result and no error for a zero base with a negative exponent (`INF`).

var_dump(fpow(0, -1));   // => float(INF)

# hypot

hypot(float $x, float $y): float

The Euclidean length `sqrt($x**2 + $y**2)`, computed without intermediate overflow.

echo hypot(3, 4);   // => 5

# fdiv

fdiv(float $num1, float $num2): float

Plain IEEE-754 division with no zero check, so a zero divisor yields `INF`, `-INF`, or `NAN` rather than aborting the way `/` does.

echo fdiv(1, 0);   // => INF

# is_nan

is_nan(float $num): bool

True when the float cast of the argument is IEEE not-a-number.

var_dump(is_nan(NAN));   // => bool(true)

# is_finite

is_finite(float $num): bool

True when the value is neither infinite nor NAN.

var_dump(is_finite(1.0));   // => bool(true)

# is_infinite

is_infinite(float $num): bool

True for positive or negative infinity.

var_dump(is_infinite(INF));   // => bool(true)

# decbin

decbin(int $num): string

The binary rendering of an integer. DIVERGENCE: PHP treats the value as unsigned 64-bit, so a negative argument gives PHP's two's-complement bit string; here it gives a leading `-` followed by the magnitude.

echo decbin(5);   // => 101

# decoct

decoct(int $num): string

The octal rendering of an integer, with the same negative-number divergence as `decbin`.

echo decoct(8);   // => 10

# bindec

bindec(string $binary_string): int|float

Parses a base-2 string, dropping a leading `0b`/`0B` and skipping any character that is not a binary digit — skipping any raises `Deprecated: Invalid characters passed for attempted conversion, these have been ignored`. The result is an integer when it fits `PHP_INT_MAX` and a float otherwise; accumulation saturates rather than wrapping.

echo bindec("101");   // => 5

# octdec

octdec(string $octal_string): int|float

Parses a base-8 string, dropping a leading `0o`/`0O` and skipping invalid digits (which raises the same `Invalid characters passed for attempted conversion` deprecation as `bindec`), with the same integer-or-float result rule.

echo octdec("10");   // => 8

# base_convert

base_convert(string $num, int $from_base, int $to_base): string

Re-renders a number from one base to another with lowercase digits, silently dropping invalid digits. A base outside `2..36` is an error. Accumulation is 128-bit and saturating, so enormous values clamp instead of wrapping.

echo base_convert("ff", 16, 2);   // => 11111111

# mt_getrandmax

mt_getrandmax(): int

Returns the constant 2147483647, the largest value `mt_rand()` produces with no arguments.

echo mt_getrandmax();   // => 2147483647

# getrandmax

getrandmax(): int

Returns the same constant 2147483647 for `rand()`.

echo getrandmax();   // => 2147483647

# srand

srand(?int $seed = null): void

Seeds the shared Mt19937 engine with the low 32 bits of `$seed`, or from clock and counter entropy when called with no argument. As in the reference, `srand` is an alias of `mt_srand`, and the one engine feeds `rand`, `mt_rand`, `shuffle`, `str_shuffle` and `array_rand` — a seeded program reproduces the reference's sequence.

# mt_srand

mt_srand(?int $seed = null, int $mode = MT_RAND_MT19937): void

Shares the `srand` arm and therefore the same Mt19937 engine (a port of `ext/random/engine_mt19937.c`). The `$mode` argument is accepted and ignored: only `MT_RAND_MT19937` is modelled.

# rand

rand(int $min = 0, int $max = 2147483647): int

A value in the inclusive range, from the shared Mt19937 engine through the reference's unbiased range reduction (`php_random_range`). Inverted bounds are swapped rather than raising. With no arguments it is the engine's 32-bit output shifted right by one.

srand(5); echo rand(1, 6);   // => 6

# mt_rand

mt_rand(int $min = 0, int $max = 2147483647): int

The same Mt19937 engine and range reduction as `rand`, except that `$min > $max` raises `Argument #2 ($max) must be greater than or equal to argument #1 ($min)`.

mt_srand(1); echo mt_rand(1, 100), " ", mt_rand();   // => 46 2141438069

# random_int

random_int(int $min, int $max): int

A uniform integer in `[$min, $max]` from the operating system's CSPRNG (the `random_bytes` source), never the seeded `mt_rand` engine, so `mt_srand` does not affect it. The mapping is `php_random_int`'s: equal bounds return without a draw, the full `PHP_INT_MIN..PHP_INT_MAX` span is the raw 64-bit draw, a power-of-two span masks, and any other span redraws above the largest multiple of the span so no value is favoured. `$min > $max` throws `ValueError: random_int(): Argument #1 ($min) must be less than or equal to argument #2 ($max)`; a CSPRNG failure throws `Random\RandomException`.

Arbitrary precision — bcmath

# bcadd

bcadd(string $num1, string $num2, ?int $scale = null): string

Exact arbitrary-precision decimal addition. The result is truncated toward zero to `$scale` fractional digits and rendered with exactly that many. `$scale` defaults to the `bcscale()` value and is clamped to `0..1048576`. An unparseable operand reads as `0` rather than raising PHP 8's `ValueError`.

echo bcadd("1.234", "5", 2);   // => 6.23

# bcsub

bcsub(string $num1, string $num2, ?int $scale = null): string

Exact decimal subtraction, with the same truncation, clamping, and lenient operand parsing as `bcadd`.

echo bcsub("5", "1.234", 2);   // => 3.76

# bcmul

bcmul(string $num1, string $num2, ?int $scale = null): string

Exact decimal multiplication, truncated toward zero to `$scale` fractional digits and padded to exactly that many.

echo bcmul("2", "3");   // => 6

# bcdiv

bcdiv(string $num1, string $num2, ?int $scale = null): string

Decimal division; a zero divisor throws `DivisionByZeroError: Division by zero`. DIVERGENCE: the quotient is computed at a 100-significant-digit context before truncation, so this is BOUNDED precision — a `$scale` needing more than about 100 significant digits is not reliable.

echo bcdiv("10", "3", 4);   // => 3.3333

# bcmod

bcmod(string $num1, string $num2, ?int $scale = null): string

The remainder `a - b * trunc(a / b)`, following PHP 7.2+ semantics. A zero divisor throws `DivisionByZeroError: Modulo by zero`. The intermediate division inherits the same bounded context as `bcdiv`.

echo bcmod("10", "3");   // => 1

# bcpow

bcpow(string $num, string $exponent, ?int $scale = null): string

Exponentiation by squaring on exact decimals. DIVERGENCE: a fractional exponent is silently truncated toward zero instead of raising PHP 8's `ValueError`, and an exponent beyond the 64-bit range saturates. A negative exponent yields the reciprocal, and zero to a negative power throws `DivisionByZeroError: Negative power of zero`.

echo bcpow("2", "10");   // => 1024

# bcsqrt

bcsqrt(string $num, ?int $scale = null): string

The square root truncated to `$scale` fractional digits. A negative operand throws `ValueError: bcsqrt(): Argument #1 ($num) must be greater than or equal to 0`. DIVERGENCE: computed at the same bounded 100-significant-digit context as `bcdiv`.

echo bcsqrt("2", 4);   // => 1.4142

# bccomp

bccomp(string $num1, string $num2, ?int $scale = null): int

Truncates both operands to `$scale` fractional digits and compares them, returning `-1`, `0`, or `1`. `$scale` defaults to the `bcscale()` value.

echo bccomp("1.001", "1", 2);   // => 0

# bcscale

bcscale(?int $scale = null): int

With no argument returns the current default scale; with one it sets the scale to `max(0, $scale)` and returns the PREVIOUS value. The scale is per-thread state, mirroring PHP's per-request scale.

bcscale(3); echo bcadd("1", "2");   // => 3.000

# bcpowmod

bcpowmod(string $num, string $exponent, string $modulus, ?int $scale = null): string

Modular exponentiation at TRUE arbitrary precision — all three operands are truncated to integers and a big-integer `modpow` does the work. A zero modulus throws `DivisionByZeroError: Modulo by zero`; a negative exponent throws `ValueError: bcpowmod(): Argument #2 ($exponent) must be greater than or equal to 0`. Because the result is an integer, `$scale` only controls how many trailing zero digits are appended.

echo bcpowmod("4", "13", "497");   // => 445

Arbitrary precision — GMP

# gmp_init

gmp_init(string|int $num, int $base = 0): string

Parses an int or an integer string (optionally signed, whitespace ignored) and returns its decimal representation as a plain STRING, not a GMP object. `$base` is 0 (auto-detect a `0x`, `0b`, `0o` or leading-`0` octal prefix) or 2 to 62; a string that is not an integer in that base throws `ValueError: gmp_init(): Argument #1 ($num) is not an integer string`. DIVERGENCE: the result is a string, not a `GMP` object.

echo gmp_init("0xff");   // => 255

# gmp_add

gmp_add(string|int $num1, string|int $num2): string

True arbitrary-precision addition, returning the sum as a decimal string.

echo gmp_add("123456789012345678901234567890", "1");   // => 123456789012345678901234567891

# gmp_sub

gmp_sub(string|int $num1, string|int $num2): string

Arbitrary-precision subtraction as a decimal string.

echo gmp_sub("100", "1");   // => 99

# gmp_mul

gmp_mul(string|int $num1, string|int $num2): string

Arbitrary-precision multiplication as a decimal string.

echo gmp_mul("99999999999", "99999999999");   // => 9999999999800000000001

# gmp_div_q

gmp_div_q(string|int $num1, string|int $num2, int $rounding_mode = GMP_ROUND_ZERO): string

Integer quotient under `$rounding_mode`: `GMP_ROUND_ZERO` truncates, `GMP_ROUND_PLUSINF` rounds up, `GMP_ROUND_MINUSINF` down; any other mode is a `ValueError`. A zero divisor throws `DivisionByZeroError: gmp_div_q(): Argument #2 ($num2) Division by zero`.

echo gmp_div_q("10", "3");   // => 3

# gmp_div

gmp_div(string|int $num1, string|int $num2, int $rounding_mode = GMP_ROUND_ZERO): string

Alias of `gmp_div_q`, including its error text.

# gmp_div_r

gmp_div_r(string|int $num1, string|int $num2, int $rounding_mode = GMP_ROUND_ZERO): string

The remainder paired with `gmp_div_q` under the same `$rounding_mode`, so `q * d + r == n`; `GMP_ROUND_ZERO` gives the remainder with the sign of the dividend. A zero divisor throws `DivisionByZeroError: gmp_div_r(): Argument #2 ($num2) Division by zero`.

# gmp_mod

gmp_mod(string|int $num1, string|int $num2): string

The non-negative remainder: the result lies in `[0, |m|)` whatever the signs. A zero modulus throws `DivisionByZeroError: Modulo by zero`.

echo gmp_mod("-7", "3");   // => 2

# gmp_pow

gmp_pow(string|int $num, int $exponent): string

Arbitrary-precision exponentiation. A negative exponent throws `ValueError: gmp_pow(): Argument #2 ($exponent) must be greater than or equal to 0`; an exponent past `u32` is a fatal error.

echo gmp_pow("2", "64");   // => 18446744073709551616

# gmp_powm

gmp_powm(string|int $num, string|int $exponent, string|int $modulus): string

Modular exponentiation at true arbitrary precision, with a non-negative result. A zero modulus throws `DivisionByZeroError: Modulo by zero` and a negative exponent `ValueError: gmp_powm(): Argument #2 ($exponent) must be greater than or equal to 0`.

echo gmp_powm("4", "13", "497");   // => 445

# gmp_gcd

gmp_gcd(string|int $num1, string|int $num2): string

The greatest common divisor by the Euclidean algorithm on absolute values, so the result is never negative.

echo gmp_gcd("12", "18");   // => 6

# gmp_lcm

gmp_lcm(string|int $num1, string|int $num2): string

The least common multiple, computed as `|a / gcd(a,b) * b|`. It returns `"0"` when either operand is zero.

echo gmp_lcm("4", "6");   // => 12

# gmp_abs

gmp_abs(string|int $num): string

The absolute value as a decimal string.

echo gmp_abs("-42");   // => 42

# gmp_neg

gmp_neg(string|int $num): string

Arithmetic negation as a decimal string.

echo gmp_neg("42");   // => -42

# gmp_and

gmp_and(string|int $num1, string|int $num2): string

Bitwise AND of the two big integers, using two's-complement semantics.

echo gmp_and("6", "3");   // => 2

# gmp_or

gmp_or(string|int $num1, string|int $num2): string

Bitwise OR of the two big integers.

echo gmp_or("6", "3");   // => 7

# gmp_xor

gmp_xor(string|int $num1, string|int $num2): string

Bitwise XOR of the two big integers.

echo gmp_xor("6", "3");   // => 5

# gmp_cmp

gmp_cmp(string|int $num1, string|int $num2): int

Compares the two big integers and returns `-1`, `0`, or `1` as a plain PHP int.

echo gmp_cmp("10", "9");   // => 1

# gmp_sign

gmp_sign(string|int $num): int

The sign of the value: `-1`, `0`, or `1`.

echo gmp_sign("-5");   // => -1

# gmp_sqrt

gmp_sqrt(string|int $num): string

The integer (floor) square root. A negative operand throws `ValueError: gmp_sqrt(): Argument #1 ($num) must be greater than or equal to 0`.

echo gmp_sqrt("17");   // => 4

# gmp_root

gmp_root(string|int $num, int $nth): string

The integer nth root, truncated toward zero. `$nth` below 1 throws `ValueError`, as does an even root of a negative number; an odd root of a negative number is the negated root of its magnitude.

echo gmp_root("27", 3);   // => 3

# gmp_fact

gmp_fact(int $num): string

The factorial. A negative argument throws `ValueError: gmp_fact(): Argument #1 ($num) must be greater than or equal to 0`. The running time is linear in `$num`.

echo gmp_fact(20);   // => 2432902008176640000

# gmp_pow2

gmp_pow2(int $exponent): string

Two raised to the given power, with a negative exponent clamped to 0. DIVERGENCE: reference PHP's GMP extension has NO `gmp_pow2()` — this function exists only in phplang. The exponent is narrowed to 32 bits.

echo gmp_pow2(10);   // => 1024

# gmp_strval

gmp_strval(string|int $num, int $base = 10): string

Renders the value in `$base`: 2 to 62 (digits `0-9a-zA-Z`, lower case up to 36) or -2 to -36 (upper case). Any other base throws `ValueError: gmp_strval(): Argument #2 ($base) must be between 2 and 62, or -2 and -36`.

echo gmp_strval("255", 16);   // => ff

# gmp_intval

gmp_intval(string|int $num): int

Converts to a PHP int the way `mpz_get_si` does: the low 63 bits of the magnitude, carrying the sign, so an out-of-range value wraps rather than saturates.

echo gmp_intval("42");   // => 42

# gmp_prob_prime

gmp_prob_prime(string|int $num, int $repetitions = 10): int

Returns 0 for composite, 1 for probably prime, and 2 for definitely prime, ignoring the sign. It trial-divides by odd divisors up to `min(sqrt(n), 100000)` — reporting 2 when that fully covers the root — then runs Miller-Rabin with the FIXED bases 2, 3, 5, 7, 11, 13, 17. DIVERGENCE: `$repetitions` is accepted and ignored, so the error bound is not tunable.

echo gmp_prob_prime("97");   // => 2

# gmp_perfect_square

gmp_perfect_square(string|int $num): bool

True when the value is non-negative and its integer square root squared equals it.

var_dump(gmp_perfect_square("16"));   // => bool(true)

# gmp_div_qr

gmp_div_qr(string|int $num1, string|int $num2, int $rounding_mode = GMP_ROUND_ZERO): array

Quotient and remainder as a two-element list, under the same `$rounding_mode` as `gmp_div_q`. A zero divisor throws `DivisionByZeroError`.

echo implode(",", gmp_div_qr("7", "2"));   // => 3,1

# gmp_divexact

gmp_divexact(string|int $num1, string|int $num2): string

Quotient of a division known to be exact. A zero divisor throws `DivisionByZeroError`.

echo gmp_divexact("12", "4");   // => 3

# gmp_gcdext

gmp_gcdext(string|int $num1, string|int $num2): array

Extended Euclid: an array with keys `g`, `s` and `t` such that `s*a + t*b == g`.

echo implode(",", gmp_gcdext("12", "18"));   // => 6,-1,1

# gmp_invert

gmp_invert(string|int $num1, string|int $num2): string|false

The modular inverse, or `false` when none exists. A zero modulus throws `DivisionByZeroError`.

echo gmp_invert("3", "7");   // => 5

# gmp_com

gmp_com(string|int $num): string

The one's complement, `-n - 1`.

echo gmp_com("5");   // => -6

# gmp_sqrtrem

gmp_sqrtrem(string|int $num): array

The floor square root and the remainder as a two-element list. A negative operand throws `ValueError`.

echo implode(",", gmp_sqrtrem("17"));   // => 4,1

# gmp_rootrem

gmp_rootrem(string|int $num, int $nth): array

The integer nth root and the remainder as a two-element list, with the argument checks of `gmp_root`.

echo implode(",", gmp_rootrem("30", 3));   // => 3,3

# gmp_binomial

gmp_binomial(string|int $n, int $k): string

The binomial coefficient C(n, k); a negative `$k` throws `ValueError`.

echo gmp_binomial(10, 3);   // => 120

# gmp_nextprime

gmp_nextprime(string|int $num): string

The smallest prime strictly greater than the operand, found with `gmp_prob_prime`.

echo gmp_nextprime("100");   // => 101

# gmp_perfect_power

gmp_perfect_power(string|int $num): bool

True when the value is `r^k` for some `k >= 2` (an odd `k` when negative); 0, 1 and -1 count.

var_dump(gmp_perfect_power("27"));   // => bool(true)

# gmp_jacobi

gmp_jacobi(string|int $num1, string|int $num2): int

The Jacobi symbol, computed as the Kronecker symbol.

echo gmp_jacobi("3", "7");   // => -1

# gmp_legendre

gmp_legendre(string|int $num1, string|int $num2): int

The Legendre symbol, computed as the Kronecker symbol.

echo gmp_legendre("3", "7");   // => -1

# gmp_kronecker

gmp_kronecker(string|int $num1, string|int $num2): int

The Kronecker symbol.

echo gmp_kronecker("3", "7");   // => -1

# gmp_popcount

gmp_popcount(string|int $num): int

The number of one bits; `-1` for a negative operand, which has infinitely many.

echo gmp_popcount("255");   // => 8

# gmp_hamdist

gmp_hamdist(string|int $num1, string|int $num2): int

The Hamming distance of two values; `-1` when their signs differ.

echo gmp_hamdist("5", "3");   // => 2

# gmp_testbit

gmp_testbit(string|int $num, int $index): bool

Whether bit `$index` is set (two's complement for a negative operand). A negative index throws `ValueError`.

var_dump(gmp_testbit("5", 2));   // => bool(true)

# gmp_scan0

gmp_scan0(string|int $num1, int $start): int

The index of the first clear bit at or above `$start`; `-1` when there is none.

echo gmp_scan0("7", 0);   // => 3

# gmp_scan1

gmp_scan1(string|int $num1, int $start): int

The index of the first set bit at or above `$start`; `-1` when there is none.

echo gmp_scan1("8", 0);   // => 3

Character classes

# ctype_alpha

ctype_alpha(mixed $text): bool

True when every byte is an ASCII letter.

var_dump(ctype_alpha("abc"), ctype_alpha("ab1"));   // => bool(true) bool(false)

# ctype_digit

ctype_digit(mixed $text): bool

True when every byte is an ASCII digit `0`-`9`.

var_dump(ctype_digit("123"));   // => bool(true)

# ctype_alnum

ctype_alnum(mixed $text): bool

True when every byte is an ASCII letter or digit.

var_dump(ctype_alnum("a1"));   // => bool(true)

# ctype_space

ctype_space(mixed $text): bool

True when every byte is space, tab, newline, vertical tab, form feed, or carriage return — matching C's `isspace`, deliberately including the vertical tab that Rust's own ASCII-whitespace test omits.

var_dump(ctype_space(" \t\n"));   // => bool(true)

# ctype_upper

ctype_upper(mixed $text): bool

True when every byte is an ASCII uppercase letter.

var_dump(ctype_upper("ABC"));   // => bool(true)

# ctype_lower

ctype_lower(mixed $text): bool

True when every byte is an ASCII lowercase letter.

var_dump(ctype_lower("abc"));   // => bool(true)

# ctype_punct

ctype_punct(mixed $text): bool

True when every byte is printable ASCII punctuation — graphic and not alphanumeric.

var_dump(ctype_punct("!?"));   // => bool(true)

# ctype_xdigit

ctype_xdigit(mixed $text): bool

True when every byte is a hexadecimal digit in either case.

var_dump(ctype_xdigit("1aF"));   // => bool(true)

# ctype_cntrl

ctype_cntrl(mixed $text): bool

True when every byte is an ASCII control character — 0x00-0x1F or 0x7F.

var_dump(ctype_cntrl("\n"));   // => bool(true)

# ctype_graph

ctype_graph(mixed $text): bool

True when every byte is printable and not a space — 0x21-0x7E.

var_dump(ctype_graph("a!"), ctype_graph("a "));   // => bool(true) bool(false)

# ctype_print

ctype_print(mixed $text): bool

True when every byte is printable, space included — 0x20-0x7E.

var_dump(ctype_print("a "));   // => bool(true)

Types and serialization

# is_scalar

is_scalar(mixed $value): bool

True only for an int, float, string, or bool. Null, arrays, objects, and closures are all false, matching PHP.

var_dump(is_scalar(1), is_scalar([]));   // => bool(true) bool(false)

# is_object

is_object(mixed $value): bool

True for a class instance, a closure or a generator; arrays are excluded. Closures and generators are `Closure` and `Generator` instances to the whole reflection surface, as in PHP. Arrays and objects share one handle representation here, so the distinction is asked of the host.

var_dump(is_object(new stdClass), is_object([]));   // => bool(true) bool(false)

# is_iterable

is_iterable(mixed $value): bool

True for an array, a generator, and an object whose class implements `Traversable`, `Iterator` or `IteratorAggregate`.

var_dump(is_iterable([1]), is_iterable(new stdClass));   // => bool(true) bool(false)

# is_countable

is_countable(mixed $value): bool

True for an array, or an object whose class implements `Countable`.

var_dump(is_countable([1]));   // => bool(true)

# get_debug_type

get_debug_type(mixed $value): string

The modern short type name: `null`, `bool`, `int`, `float`, `string`, `array`, `Closure`, or the class name. Use `gettype()` for PHP's legacy long names.

echo get_debug_type(1.5), "|", get_debug_type(null);   // => float|null

# serialize

serialize(mixed $value): string

Emits PHP's serialization format using `serialize_precision=-1` float rules: `a:` for arrays, `O:` for objects (with the engine's NUL-mangled visibility keys), `E:` for enum cases. An object's `__serialize` answer replaces its properties; failing that, `__sleep` names the ones written, with the reference's warnings for a name that does not exist or repeats. DIVERGENCE: a structure that contains ITSELF is written as `N;` at the repeat, where the reference emits an `r:`/`R:` back-reference — the output stays finite and valid but no longer round-trips a cycle.

echo serialize([1, "a"]);   // => a:2:{i:0;i:1;i:1;s:1:"a";}

# unserialize

unserialize(string $data): mixed

Parses the `N b i d s a O E` tags and returns `false` on malformed input, trailing bytes, or a negative array count; an oversized `i:` saturates with the reference's warning. An `O:` object starts from its class defaults without running the constructor, then `__unserialize` or `__wakeup` runs once the whole payload has parsed, in the order the objects were finished; an unknown class becomes `__PHP_Incomplete_Class`. DIVERGENCE: `C:` and reference (`R:`/`r:`) records are unsupported, and the `$options` argument is not read.

print_r(unserialize('a:1:{i:0;i:5;}'));   // => Array\n(\n    [0] => 5\n)

Regular expressions

# preg_match

preg_match(string $pattern, string $subject, array &$matches = [], int $flags = 0, int $offset = 0): int|false

Returns 1 on a match, 0 on none, or `false` for a pattern that will not compile — which also raises `Warning: preg_match(): <reason>` and leaves `preg_last_error()` at `PREG_INTERNAL_ERROR`. `$matches` is a real by-reference out-parameter and is written whether or not the caller initialised it. `PREG_OFFSET_CAPTURE` and `PREG_UNMATCHED_AS_NULL` are both honoured. `$offset` moves where the SEARCH starts without slicing the subject, so `^` still anchors to the real start and reported offsets are measured from it.

preg_match("/(\d+)/", "ab 42", $m); echo $m[1];   // => 42

# preg_match_all

preg_match_all(string $pattern, string $subject, array &$matches = [], int $flags = PREG_PATTERN_ORDER, int $offset = 0): int|false

Returns the number of matches, or `false` for a pattern that will not compile, with the same `Warning` and `preg_last_error()` state as `preg_match`. `$matches` is a real by-reference out-parameter, keyed by group name as well as index. `PREG_SET_ORDER` truncates each set at its own last participating group, so its rows are ragged where `PREG_PATTERN_ORDER`'s columns are full width. `PREG_OFFSET_CAPTURE` and `PREG_UNMATCHED_AS_NULL` are honoured alongside the order bit, and `$offset` moves where the search starts without slicing the subject.

$m = []; echo preg_match_all("/\d/", "a1b2", $m), $m[0][1];   // => 22

# preg_replace

preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null

Applies each pattern in turn. `$replacement` may be one string for every pattern or an array index-matched to the patterns (surplus patterns replace with `""`). The `$1`, `${1}`, and `\1` back-reference forms all work in the REPLACEMENT even though back-references in the pattern do not. A pattern that will not compile raises `Warning: preg_replace(): <reason>` once per subject and leaves that subject without a result — null for a string subject, a dropped element for an array one; a string `$pattern` with an array `$replacement` is a `TypeError`. `&$count` receives the total number of replacements across every pattern, and is written even when that total is zero.

echo preg_replace("/\d+/", "#", "a1b22");   // => a#b#

# preg_filter

preg_filter(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null

`preg_replace` that keeps only the subjects a pattern actually replaced something in: a string subject with no replacement is null, and an array subject loses those elements (keys preserved).

var_dump(preg_filter("/\d/", "#", ["a1", "b"]));   // => array(1) { [0]=> string(2) "a#" }

# preg_replace_callback

preg_replace_callback(string|array $pattern, callable $callback, string|array $subject, int $limit = -1, int &$count = null, int $flags = 0): string|array|null

Calls the callback for each match with a fully POPULATED `$matches` array. `$limit` is honoured, and a pattern that will not compile returns null after raising `Warning: preg_replace_callback(): <reason>`. `&$count` receives the number of replacements, and `$flags` takes `PREG_OFFSET_CAPTURE`/`PREG_UNMATCHED_AS_NULL`, which reshape the `$matches` the callback receives.

echo preg_replace_callback("/\d/", fn($m) => $m[0] * 2, "a1b2");   // => a2b4

# preg_replace_callback_array

preg_replace_callback_array(array $pattern, string|array $subject, int $limit = -1, int &$count = null, int $flags = 0): string|array|null

Applies each `pattern => callback` entry in turn to the WHOLE subject — every element of an array subject — before the next entry runs, so later patterns see earlier replacements. `$limit` bounds each pattern on each string, `&$count` totals every replacement, and `$flags` reshapes `$matches` as for `preg_replace_callback`. A value in the map that is not callable raises `TypeError: preg_replace_callback_array(): Argument #1 ($pattern) must contain only valid callbacks` before anything runs; a pattern that will not compile warns and the result is null.

echo preg_replace_callback_array(["/\d+/" => fn($m) => "N", "/[a-z]+/" => fn($m) => "W"], "abc 123");   // => W N

# preg_split

preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array|false

Splits on each match. All three flag bits are honoured: `PREG_SPLIT_NO_EMPTY`, `PREG_SPLIT_DELIM_CAPTURE`, and `PREG_SPLIT_OFFSET_CAPTURE`. A zero-width match sitting right after a non-empty one is emitted, as PCRE does, so `/x*/` and `/\d*/` split the way the reference splits them. The captured delimiters `PREG_SPLIT_DELIM_CAPTURE` interleaves are positional — unlike `$matches`, they are not keyed by group name.

echo implode("-", preg_split("/[\s,]+/", "a, b  c"));   // => a-b-c

# preg_quote

preg_quote(string $str, ?string $delimiter = null): string

Backslash-escapes the PCRE special set `.\+*?[^]$(){}=!<>|:-#`, plus the first character of `$delimiter` when supplied. A NUL byte becomes the four-character sequence `\000`. It compiles nothing, so it never touches `preg_last_error()`.

echo preg_quote("1+1");   // => 1\+1

# preg_grep

preg_grep(string $pattern, array $array, int $flags = 0): array|false

The entries whose string value matches the pattern, PRESERVING keys. The `PREG_GREP_INVERT` bit inverts the test. A non-array subject yields an empty array rather than raising.

echo implode(",", preg_grep("/^a/", ["apple", "pear"]));   // => apple

# preg_last_error

preg_last_error(): int

The outcome of the last `preg_*` call that reached the regex compiler: `PREG_INTERNAL_ERROR` (1) after a pattern the engine rejected, `PREG_NO_ERROR` (0) after one it accepted. The state is STICKY and cleared only by another compile — reading it does not clear it, and `preg_quote()` does not touch it — so a pattern that compiles resets it even when the match then finds nothing. DIVERGENCE: only these two codes are produced; the reference also reports backtrack- and recursion-limit exhaustion, which this engine has no equivalent of.

@preg_match("/[a", "x"); echo preg_last_error();   // => 1

# preg_last_error_msg

preg_last_error_msg(): string

The message for the `preg_last_error()` code, and like it a pure reader that clears nothing. `"No error"` or `"Internal error"` in practice, the two codes this engine produces.

@preg_match("/[a", "x"); echo preg_last_error_msg();   // => Internal error

JSON

# json_decode

json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed

A hand-written recursive-descent parser over the raw bytes. A JSON array always decodes to a PHP array; a JSON object decodes to a `stdClass` unless `$associative` is truthy, or it is left null and `$flags` carries `JSON_OBJECT_AS_ARRAY`. Objects take their creation-order handles where `ext/json` allocates them — as each object's first member closes — so `json_decode('{"a":{"b":1}}')` numbers the inner `#1` and the outer `#2`. `$depth` is honoured and RANGE-CHECKED: below 1 raises `ValueError: json_decode(): Argument #3 ($depth) must be greater than 0` and past `INT_MAX` raises `… must be less than 2147483647`. `JSON_THROW_ON_ERROR` and `JSON_BIGINT_AS_STRING` are honoured. Integral numbers become ints; anything with a `.`/`e` becomes a float, as does an integer beyond the 64-bit range — unless `JSON_BIGINT_AS_STRING` keeps it as the string of its digits. Any other failure returns null and records the code for `json_last_error()`. DIVERGENCE: the parser recurses on the native stack, so nesting deeper than 1024 reports `JSON_ERROR_DEPTH` whatever `$depth` asked for.

echo json_decode('{"a":1}')->a;   // => 1

# json_validate

json_validate(string $json, int $depth = 512, int $flags = 0): bool

Runs the same grammar without allocating any array and returns whether the input is well-formed, setting `json_last_error()` either way. `$depth` follows the same default-512, clamp-to-1 rule; `$flags` is ignored.

var_dump(json_validate('{"a":1}'), json_validate('{'));   // => bool(true) bool(false)

# json_last_error

json_last_error(): int

The `JSON_ERROR_*` code from the last `json_encode`, `json_decode` or `json_validate` call. DIVERGENCE: PHP keeps this per request; here it is thread-local state that lives for the thread's lifetime.

json_decode("{"); echo json_last_error();   // => 4

# json_last_error_msg

json_last_error_msg(): string

The message matching `json_last_error()`, using PHP's own wording — `No error`, `Maximum stack depth exceeded`, `State mismatch (invalid or malformed JSON)`, `Control character error, possibly incorrectly encoded`, `Syntax error`, `Malformed UTF-8 characters, possibly incorrectly encoded`, `Recursion detected`, `Inf and NaN cannot be JSON encoded`, `Type is not supported`, `The decoded property name is invalid`, `Single unpaired UTF-16 surrogate in unicode escape`, or `Non-backed enums have no default serialization`.

json_decode("{"); echo json_last_error_msg();   // => Syntax error

Encoding

# base64_encode

base64_encode(string $string): string

Standard padded base64 with the `+`/`/` alphabet, over the UTF-8 bytes of the argument.

echo base64_encode("abc");   // => YWJj

# base64_decode

base64_decode(string $string, bool $strict = false): string|false

A faithful port of PHP's own decoder, including its reverse table which skips tab, newline, carriage return, and space. `$strict` is honoured and rejects an invalid character, data after padding, a truncated final group, and wrong padding length. Non-strict mode silently skips unrecognized bytes.

echo base64_decode("YWJj");   // => abc

# hex2bin

hex2bin(string $string): string|false

Decodes a hex string to bytes, returning `false` on an odd length or a non-hex character. The counterpart `bin2hex` lives in the core library, not this module.

echo hex2bin("616263");   // => abc

# quoted_printable_encode

quoted_printable_encode(string $string): string

A port of PHP's encoder: soft-wraps at 75 columns with `=` and CRLF, and emits `=XX` in uppercase hex for control bytes, 0x7F, high bytes, `=` itself, and a space directly before a carriage return.

echo quoted_printable_encode("a=b");   // => a=3Db

# quoted_printable_decode

quoted_printable_decode(string $string): string

Decodes `=XX` sequences, removes soft line breaks, drops a trailing bare `=`, and passes any other malformed `=` through verbatim — matching PHP.

echo quoted_printable_decode("a=3Db");   // => a=b

# convert_uuencode

convert_uuencode(string $string): string

A port of PHP's uuencoder: 45-byte lines each prefixed by an encoded length character, three bytes to four printable characters, sextet zero mapped to a backtick, and a backtick-plus-newline trailer.

echo trim(convert_uudecode(convert_uuencode("abc")));   // => abc

# convert_uudecode

convert_uudecode(string $string): string|false

A port of PHP's uudecoder including its sanity checks: `false` for empty input, a declared line length larger than the buffer, an overrunning encoded span, or nothing decoded. A zero-length (backtick) line terminates.

# utf8_encode

utf8_encode(string $string): string

The deprecated Latin-1 to UTF-8 shim (`Deprecated: Function utf8_encode() is deprecated since 8.2` on every call): each BYTE is widened to the codepoint of the same value, so `"\xE9"` becomes `é` and already-multibyte input becomes mojibake, as in the reference.

echo utf8_encode("abc");   // => abc

# utf8_decode

utf8_decode(string $string): string

The deprecated UTF-8 to Latin-1 shim (`Deprecated: Function utf8_decode() is deprecated since 8.2` on every call): each codepoint at or below U+00FF is narrowed to its one byte, and one above it — or an invalid UTF-8 unit, grouped as `htmlspecialchars` groups them — becomes `?`.

echo bin2hex(utf8_decode("é")), "|", utf8_decode("€");   // => e9|?

# iconv

iconv(string $from_encoding, string $to_encoding, string $string): string|false

Converts between UTF-8, ASCII, ISO-8859-1, ISO-8859-15, CP1252, UTF-16/UCS-2 and UTF-32/UCS-4, under every name the reference's libiconv accepts for them (`LATIN1`, `UNICODELITTLE`, `UCS-2-INTERNAL`, …). Plain `UTF-16`/`UTF-32` write a big-endian BOM and read one anywhere in the input. What the platform libiconv does beyond the charsets is measured off the reference by `scripts/gen_iconv_tables.php`: its 8-bit converters spell a character they lack even without `//TRANSLIT` (`Œ` → `OE` in ISO-8859-1), and `//TRANSLIT` adds its transliterations (`é` → `'e` in ASCII, `€` → `EUR`). `//IGNORE` on the target drops what is left and skips input bytes that cannot start a character. A character the target cannot hold, or input not valid in the source charset, is `false` with `Notice: iconv(): Detected an illegal character in input string` (`an incomplete multibyte character` for a sequence cut short at the end). An unknown charset is `false` with `Warning: iconv(): Wrong encoding, conversion from "X" to "Y" is not allowed`. DIVERGENCE: other charsets are unknown, and every transliteration is spelled in full where the reference's libiconv 1.11 garbles some multi-character `//TRANSLIT` results (16 × `€` to ASCII comes back with `?` in places 7 and 14).

echo iconv("UTF-8", "ASCII//TRANSLIT", "café");   // => caf'e

# iconv_strlen

iconv_strlen(string $string, ?string $encoding = null): int|false

The number of characters in `$string` decoded from `$encoding` (UTF-8 by default). Input that does not decode is `false` with `Notice: iconv_strlen(): Detected an illegal character in input string`.

echo iconv_strlen("héllo");   // => 5

# iconv_substr

iconv_substr(string $string, int $offset, ?int $length = null, ?string $encoding = null): string|false

`substr` by character rather than byte, with the same negative `$offset`/`$length` rules.

echo iconv_substr("héllo", 1, 2);   // => él

# iconv_strpos

iconv_strpos(string $haystack, string $needle, int $offset = 0, ?string $encoding = null): int|false

The character position of the first `$needle` at or after `$offset` (negative counts from the end). An empty needle or an offset outside the haystack is a `ValueError`.

echo iconv_strpos("héllo", "l");   // => 2

# iconv_strrpos

iconv_strrpos(string $haystack, string $needle, ?string $encoding = null): int|false

The character position of the last `$needle`, `false` when absent or empty.

echo iconv_strrpos("héllo", "l");   // => 3

# iconv_get_encoding

iconv_get_encoding(string $type = "all"): array|string|false

The `iconv.*_encoding` settings, all `UTF-8` (the reference's defaults); `"all"` returns the three as an array keyed `input_encoding`, `output_encoding`, `internal_encoding`.

echo iconv_get_encoding("internal_encoding");   // => UTF-8

URL

# urlencode

urlencode(string $string): string

RFC 1738 percent-encoding over the string's bytes: letters, digits, `-`, `_`, and `.` pass through, a space becomes `+`, and everything else — the tilde included — becomes an uppercase `%XX`.

echo urlencode("a b&c");   // => a+b%26c

# urldecode

urldecode(string $string): string

Decodes `%XX` escapes and maps `+` back to a space. A `%` not followed by two hex digits is emitted verbatim, matching PHP. Note a `%XX` sitting at the very END of the string is not decoded.

echo urldecode("a+b%26c");   // => a b&c

# rawurlencode

rawurlencode(string $string): string

RFC 3986 percent-encoding: letters, digits, `-`, `_`, `.`, and `~` pass through (the tilde is preserved, unlike `urlencode`), and a space becomes `%20`.

echo rawurlencode("a b~c");   // => a%20b~c

# rawurldecode

rawurldecode(string $string): string

The `urldecode` decoder with plus-to-space turned off, so `+` stays literal. It shares the same end-of-string `%XX` behaviour.

echo rawurldecode("a%20b+c");   // => a b+c

# http_build_query

http_build_query(array $data, string $numeric_prefix = "", ?string $arg_separator = "&", int $encoding_type = PHP_QUERY_RFC1738): string|false

Serializes recursively to `k=v` pairs, url-encoding keys and values. All four arguments are honoured: `$numeric_prefix` is prepended to top-level integer keys, an explicit empty separator is respected, and `$encoding_type == 2` switches to `rawurlencode`. Nested arrays become `key[sub]` segments, null leaves are skipped, and booleans serialize as `1`/`0`. A non-array subject returns `false`.

echo http_build_query(["a" => 1, "b" => 2]);   // => a=1&b=2

# parse_url

parse_url(string $url, int $component = -1): array|string|int|null|false

A faithful port of PHP's own parser, so relative schemes, `mailto:`, bracketed IPv6 hosts, schemeless `host:port`, and the `file:///c:/` drive case all match reference PHP. Control bytes in each component are replaced with `_`. A non-negative `$component` selects one piece by its `PHP_URL_*` ordinal; ANY negative one asks for the whole array, and a positive one past `PHP_URL_FRAGMENT` raises `ValueError: parse_url(): Argument #2 ($component) must be a valid URL component identifier, N given` before the URL is even parsed. An out-of-range port, an empty host, or a bad authority returns `false`.

echo parse_url("https://example.com/p?q=1")["host"];   // => example.com

# parse_str

parse_str(string $string): array

Parses a query string into an array, handling `key[]` appends, `key[sub]` nesting, and PHP's mangling of interior `.` and space to `_` in top-level keys. DIVERGENCE: PHP writes into a by-reference second argument and returns void; phplang has no by-reference out-parameter, so this RETURNS the array instead — write `$r = parse_str($s);`.

$r = parse_str("a=1&b=2"); echo $r["a"], $r["b"];   // => 12

Hashing

# md5

md5(string $string, bool $binary = false): string

MD5 of the argument's bytes, as 32 lowercase hex characters, or the 16 raw digest bytes with `$binary`.

echo md5("abc");   // => 900150983cd24fb0d6963f7d28e17f72

# sha1

sha1(string $string, bool $binary = false): string

SHA-1 as 40 lowercase hex characters, or the 20 raw digest bytes when `$binary` is truthy.

echo sha1("abc");   // => a9993e364706816aba3e25717850c26c9cd0d89d

# crc32

crc32(string $string): int

The reflected CRC-32 (the zlib polynomial) as a PHP integer. No second argument is read.

echo crc32("abc");   // => 891568578

# hash

hash(string $algo, string $data, bool $binary = false, array $options = []): string

Digests the data with any algorithm `hash_algos()` lists: the MD, SHA-1/2/3, RIPEMD, Whirlpool, 3-pass Tiger and GOST digests, the `adler32`/`crc32*`/`fnv*`/`joaat` checksums, and the `murmur3*`/`xxh*` hashes. `$options` is read by `murmur3*` and `xxh*` only: `seed` (an int; any other type is the reference's `Deprecated:` and seed 0, or for `xxh3`/`xxh128` ignored), and for `xxh3`/`xxh128` a `secret` string of at least 136 bytes (more than 256 is truncated with a warning; `seed` and `secret` together are an `Error`). An unknown name throws `ValueError: hash(): Argument #1 ($algo) must be a valid hashing algorithm`. DIVERGENCE: `tiger*,4`, `snefru`, `snefru256` and `haval*` are not implemented and throw as unknown.

echo hash("sha256", "");   // => e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

# hash_hmac

hash_hmac(string $algo, string $data, string $key, bool $binary = false): string

RFC 2104 HMAC over the cryptographic digests of `hash()`, with the block size paired per algorithm; the checksums (`adler32`, `crc32*`, `fnv*`, `joaat`) are rejected. An unknown or non-cryptographic name throws `ValueError: hash_hmac(): Argument #1 ($algo) must be a valid cryptographic hashing algorithm`. `$key` is `#[\SensitiveParameter]`, so a backtrace prints it as `Object(SensitiveParameterValue)` rather than the key itself.

echo strlen(hash_hmac("sha256", "m", "k"));   // => 64

# hash_algos

hash_algos(): array

The implemented algorithms, in the reference's relative order. DIVERGENCE: the reference also lists `tiger*,4`, `snefru`, `snefru256` and the fifteen `haval*` variants (see `hash`), so the count differs.

echo in_array("sha3-256", hash_algos()) ? "yes" : "no";   // => yes

# hash_hmac_algos

hash_hmac_algos(): array

The algorithms `hash_hmac`, `hash_hmac_file`, `hash_pbkdf2` and `hash_init` with `HASH_HMAC` accept: `hash_algos()` without the checksums and the `murmur3*`/`xxh*` hashes, in the same order. DIVERGENCE: as for `hash_algos`, the unimplemented `tiger*,4`, `snefru*` and `haval*` are absent.

echo in_array("ripemd160", hash_hmac_algos()) ? "yes" : "no";   // => yes

Hashing — files and key derivation

# md5_file

md5_file(string $filename, bool $binary = false): string|false

MD5 of the file's RAW bytes read straight off disk, so unlike the string functions this is byte-faithful for binary files. An empty path is `ValueError: Path must not be empty`; a file that cannot be opened is the stream layer's `Failed to open stream` warning and `false`, a directory its `Read of 8192 bytes failed` notice and `false`.

# sha1_file

sha1_file(string $filename, bool $binary = false): string|false

SHA-1 of the file's raw bytes. An unreadable path is diagnosed as for `md5_file` and returns `false`.

# hash_file

hash_file(string $algo, string $filename, bool $binary = false, array $options = []): string|false

Validates the algorithm BEFORE touching the filesystem, matching PHP. It accepts every algorithm and `$options` `hash()` does; the options are read after the file is opened, as the reference reads them. An unreadable path is diagnosed as for `md5_file` and returns `false`.

# hash_hmac_file

hash_hmac_file(string $algo, string $filename, string $key, bool $binary = false): string|false

HMACs the file's raw bytes under the key. It accepts the same algorithms as `hash_hmac`, validated before the read; an unreadable path is diagnosed as for `md5_file` and returns `false`.

# hash_equals

hash_equals(string $known_string, string $user_string): bool

A timing-safe comparison: it returns false immediately on a length mismatch (length is not treated as secret, as in PHP) and otherwise ORs the per-byte XOR across the whole length, so the running time does not reveal where the first difference is.

var_dump(hash_equals("abc", "abc"));   // => bool(true)

# hash_pbkdf2

hash_pbkdf2(string $algo, string $password, string $salt, int $iterations, int $length = 0, bool $binary = false): string

PBKDF2 per RFC 2898 over the local HMAC, accepting `md5`, `sha1`, `sha256`, `sha384`, `sha512`. `$length` is the length of the OUTPUT STRING — derived bytes for binary output, hex characters otherwise — and 0 emits the full digest. Throws a `ValueError` on an unknown algorithm, non-positive iterations, or a negative length. `$password` is `#[\SensitiveParameter]`, so a backtrace prints it as `Object(SensitiveParameterValue)`. DIVERGENCE: a length above 16777216 is refused (PHP instead attempts the allocation and dies on the memory limit).

echo strlen(hash_pbkdf2("sha256", "p", "s", 10, 20));   // => 20

# random_bytes

random_bytes(int $length): string

`$length` raw bytes from the operating system's CSPRNG, per `ext/random/csprng.c`: `CCRandomGenerateBytes` on macOS, `arc4random_buf` on OpenBSD/NetBSD/Haiku, and `getrandom` falling back to `/dev/urandom` elsewhere. A failure throws `Random\RandomException` with the reference's text (`Cannot open /dev/urandom: …`, `Could not gather sufficient random data`, …). A length below 1 throws `ValueError: random_bytes(): Argument #1 ($length) must be greater than 0`. DIVERGENCE: a length above 16 MiB is refused with a `ValueError` too (PHP instead attempts the allocation and dies on the memory limit).

# hash_init

hash_init(string $algo, int $flags = 0, string $key = "", array $options = []): HashContext

Opens an incremental hashing context for any algorithm `hash()` accepts; `$options` seeds a `murmur3*`/`xxh*` context exactly as it does for `hash()`, and `hash_copy` carries the seed or secret; with `HASH_HMAC` in `$flags` the context HMACs under `$key`, which must then be a cryptographic algorithm and a non-empty key. The three refusals are the reference's `ValueError`s. `var_dump` and `print_r` show the context's `algo`. DIVERGENCE: the context accumulates its input and digests it at `hash_final` rather than streaming it, so feeding it gigabytes holds them in memory; `serialize` writes phplang's own state, not the reference's digest-internal array; two contexts compare `==` by algorithm and state where the reference compares them equal.

$c = hash_init("sha256"); hash_update($c, "ab"); hash_update($c, "c"); echo hash_final($c);   // => ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

# hash_update

hash_update(HashContext $context, string $data): bool

Feeds a string's bytes to the context; always `true`. Anything but a `HashContext` is `TypeError: hash_update(): Argument #1 ($context) must be of type HashContext, int given`, and a context `hash_final` has closed is `… must be a valid, non-finalized HashContext`.

$c = hash_init("md5"); var_dump(hash_update($c, "x"));   // => bool(true)

# hash_update_stream

hash_update_stream(HashContext $context, $stream, int $length = -1): int

Feeds up to `$length` bytes from the stream's cursor — everything left when `$length` is negative — and returns how many were read. A non-resource second argument is `TypeError: … Argument #2 ($stream) must be of type resource, int given`.

$fp = fopen(__FILE__, "r"); $c = hash_init("sha1"); echo hash_update_stream($c, $fp, 5);   // => 5

# hash_update_file

hash_update_file(HashContext $context, string $filename, $stream_context = null): bool

Feeds a file's raw bytes to the context: `true`, or `false` after the stream layer's `Failed to open stream` warning (a directory is its `Read of 8192 bytes failed … Is a directory` notice). An empty path is `ValueError: Path must not be empty`.

$c = hash_init("sha1"); var_dump(hash_update_file($c, "/nonexistent"));   // => Warning … bool(false)

# hash_final

hash_final(HashContext $context, bool $binary = false): string

The digest of everything fed so far — the HMAC, for a context opened with `HASH_HMAC` — as lowercase hex, or raw bytes with `$binary`. The context is then finalized: `hash_update`, `hash_final` and `hash_copy` on it are the reference's `TypeError`.

$c = hash_init("sha256", HASH_HMAC, "key"); hash_update($c, "The quick brown fox jumps over the lazy dog"); echo hash_final($c);   // => f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8

# hash_copy

hash_copy(HashContext $context): HashContext

An independent context in the same state: later updates to either do not reach the other. `clone $context` is the same copy. A finalized context is refused with the `valid, non-finalized` `TypeError`.

$a = hash_init("md5"); hash_update($a, "a"); $b = hash_copy($a); hash_update($b, "b"); echo hash_final($a) === md5("a") && hash_final($b) === md5("ab") ? "independent" : "shared";   // => independent

Date and time

# time

time(): int

The current Unix timestamp in whole seconds. Any arguments passed are ignored.

var_dump(time() > 1700000000);   // => bool(true)

# mktime

mktime(int $hour = ?, int $minute = ?, int $second = ?, int $month = ?, int $day = ?, int $year = ?): int|false

Builds a timestamp in UTC ONLY, with each omitted field defaulting to the corresponding component of the current UTC time. Out-of-range fields normalize (month 13 rolls to next January, day 0 to the previous month's last day), and two-digit years map 0-69 to 2000-2069 and 70-100 to 1970-2000. DIVERGENCE: an overflow returns `false` rather than a far-future timestamp.

echo mktime(0, 0, 0, 1, 1, 1970);   // => 0

# gmmktime

gmmktime(int $hour = ?, int $minute = ?, int $second = ?, int $month = ?, int $day = ?, int $year = ?): int|false

Shares the `mktime` arm and is therefore identical to it.

echo gmmktime(0, 0, 0, 1, 1, 1970);   // => 0

# date

date(string $format, int $timestamp = time()): string

The timestamp broken down in the default zone and rendered by a port of the reference's `date_format`: every format character, including the zone ones (`e T O P p Z I`), Swatch time `B`, ISO week `W`/`o` and the expanded years `x`/`X`; a backslash escapes the next character.

echo date("Y-m-d H:i:s T", 0);   // => 1970-01-01 00:00:00 UTC

# gmdate

gmdate(string $format, int $timestamp = time()): string

As `date`, but in UTC with the zone reported as GMT (`T` is `GMT`, `e` is `UTC`).

echo gmdate("Y-m-d T", 0);   // => 1970-01-01 GMT

# checkdate

checkdate(int $month, int $day, int $year): bool

True when the month is 1-12, the year is 1-32767, and the day is within that month under the proleptic Gregorian leap rule. Missing arguments read as 0 and therefore fail.

var_dump(checkdate(2, 29, 2024), checkdate(2, 30, 2024));   // => bool(true) bool(false)

# idate

idate(string $format, ?int $timestamp = null): int|false

One `date()` field as an int (`php_idate`): `d j N w z W m n t L y Y o B g h H G i s I Z U`. A format longer than one character, or an unknown one, warns and returns `false`.

echo idate("Y", 0), idate("z", 86400 * 40);   // => 197040

# microtime

microtime(bool $as_float = false): float|string

With a truthy argument the timestamp as a float; otherwise the classic `"0.12345678 1712345678"` string with the fraction first.

var_dump(microtime(true) > 0);   // => bool(true)

# strtotime

strtotime(string $datetime, ?int $baseTimestamp = null): int|false

timelib's free-form scanner, ported rule for rule: ISO, American, textual and pointed dates, 12- and 24-hour times, `@<seconds>[.<fraction>]`, zone offsets and abbreviations, ISO weeks, relative offsets (`+1 week 2 days`, `3 days ago`, `+5 weekdays`), weekday and "first/last … of" phrases, `next`/`last`/`this`. Holes are filled from the base timestamp in the default zone. `false` when the scanner reports an error. DIVERGENCE: a zone identifier resolves only when its offset is fixed (no tz database).

echo date("Y-m-d", strtotime("last friday of next month", 0));   // => 1970-02-27

# getdate

getdate(int $timestamp = time()): array

A UTC-computed map with the keys `seconds minutes hours mday wday mon year yday weekday month` plus the integer key `0` holding the timestamp. DIVERGENCE: only key `0` is numeric — PHP's other numeric indices are absent.

echo getdate(0)["year"], getdate(0)["weekday"];   // => 1970Thursday

# date_default_timezone_set

date_default_timezone_set(string $timezoneId): true

Stores the name and ALWAYS returns true. A fixed-offset zone (`UTC`, `Etc/GMT+5`) then shifts the date functions; any other name is computed as UTC. DIVERGENCE: an unknown name is not rejected (PHP returns false), and a zone with transitions cannot be honoured without a tz database.

var_dump(date_default_timezone_set("America/New_York"));   // => bool(true)

# date_default_timezone_get

date_default_timezone_get(): string

The name last stored, defaulting to `UTC`. It round-trips whatever string was set, valid or not.

echo date_default_timezone_get();   // => UTC

Date and time — object API

# date_create

date_create(string $datetime = "now", ?DateTimeZone $timezone = null): DateTime|false

`new DateTime($datetime, $timezone)`, except that a string the scanner refuses returns `false` instead of throwing.

echo date_create("@0")->format("Y");   // => 1970

# date_create_immutable

date_create_immutable(string $datetime = "now", ?DateTimeZone $timezone = null): DateTimeImmutable|false

The `DateTimeImmutable` counterpart of `date_create`.

echo date_create_immutable("@0")->getTimestamp();   // => 0

# date_create_from_format

date_create_from_format(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false

Parses `$datetime` against `$format` with a port of `timelib_parse_from_format`; fields the format does not set come from the current time unless `!` or `|` resets them. `false` on any parse error.

echo date_create_from_format("d/m/Y", "15/08/2024")->format("Y-m-d");   // => 2024-08-15

# date_create_immutable_from_format

date_create_immutable_from_format(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false

The `DateTimeImmutable` counterpart of `date_create_from_format`.

echo date_create_immutable_from_format("!Y", "2024")->format("c");   // => 2024-01-01T00:00:00+00:00

# date_interval_create_from_date_string

date_interval_create_from_date_string(string $datetime): DateInterval|false

A `DateInterval` holding the RELATIVE part of a strtotime string (`3 days`, `last monday`). A string with an absolute date, time or zone warns `contains non-relative elements` and returns `false`.

echo date_interval_create_from_date_string("1 day")->d;   // => 1

# date_format

date_format(DateTimeInterface $object, string $format): string

`$object->format($format)`.

echo date_format(date_create("@0"), "Y-m-d");   // => 1970-01-01

# date_add

date_add(DateTime $object, DateInterval $interval): DateTime

Adds the interval in place (calendar fields first, then the clock) and returns the object.

echo date_add(date_create("@0"), new DateInterval("P1D"))->getTimestamp();   // => 86400

# date_sub

date_sub(DateTime $object, DateInterval $interval): DateTime

Subtracts the interval in place. A weekday or special relative interval warns and leaves the date alone.

echo date_sub(date_create("@86400"), new DateInterval("P1D"))->getTimestamp();   // => 0

# date_diff

date_diff(DateTimeInterface $baseObject, DateTimeInterface $targetObject, bool $absolute = false): DateInterval

timelib's `timelib_diff`: years, months and days borrowed against the calendar, `days` the whole-day count, `invert` set when the target is earlier (cleared by `$absolute`).

echo date_diff(date_create("2024-01-31"), date_create("2024-03-01"))->format("%m %d %a");   // => 0 30 30

# date_modify

date_modify(DateTime $object, string $modifier): DateTime|false

Applies a strtotime string to the object in place. A string the scanner refuses warns `Failed to parse time string` and returns `false`.

echo date_modify(date_create("@0"), "+1 day")->getTimestamp();   // => 86400

# date_timestamp_get

date_timestamp_get(DateTimeInterface $object): int

`$object->getTimestamp()`.

echo date_timestamp_get(date_create("@42"));   // => 42

# date_timestamp_set

date_timestamp_set(DateTime $object, int $timestamp): DateTime

Moves the object to the timestamp, in its own zone, and drops the microseconds.

echo date_timestamp_set(date_create("@0"), 99)->getTimestamp();   // => 99

# date_date_set

date_date_set(DateTime $object, int $year, int $month, int $day): DateTime

Sets the calendar date, normalizing an out-of-range month or day.

echo date_date_set(date_create("@0"), 2024, 2, 30)->format("Y-m-d");   // => 2024-03-01

# date_isodate_set

date_isodate_set(DateTime $object, int $year, int $week, int $dayOfWeek = 1): DateTime

Sets the date from an ISO year, week and weekday.

echo date_isodate_set(date_create("@0"), 2024, 1)->format("Y-m-d");   // => 2024-01-01

# date_time_set

date_time_set(DateTime $object, int $hour, int $minute, int $second = 0, int $microsecond = 0): DateTime

Sets the clock, carrying an out-of-range field into the date.

echo date_time_set(date_create("@0"), 25, 0)->format("Y-m-d H:i");   // => 1970-01-02 01:00

# date_timezone_get

date_timezone_get(DateTimeInterface $object): DateTimeZone|false

The object's zone as a `DateTimeZone`.

echo date_timezone_get(date_create("2024-01-01 +05:30"))->getName();   // => +05:30

# date_timezone_set

date_timezone_set(DateTime $object, DateTimeZone $timezone): DateTime

Keeps the instant and moves the object into `$timezone`.

echo date_timezone_set(date_create("@0"), timezone_open("+02:00"))->format("H:i");   // => 02:00

# date_offset_get

date_offset_get(DateTimeInterface $object): int

The object's offset from UTC in seconds.

echo date_offset_get(date_create("2024-01-01 EST"));   // => -18000

# date_interval_format

date_interval_format(DateInterval $object, string $format): string

`$object->format($format)`: `%Y %y %M %m %D %d %H %h %I %i %S %s %F %f %a %R %r %%`; any other `%x` is copied as written.

echo date_interval_format(new DateInterval("P2D"), "%d %a");   // => 2 (unknown)

# date_parse

date_parse(string $datetime): array

What the scanner read, unresolved: the fields it set (`false` for the rest), the warnings and errors by position, the zone, and the relative part.

echo date_parse("2024-02-30 10:00")["warnings"][17];   // => The parsed date was invalid

# date_parse_from_format

date_parse_from_format(string $format, string $datetime): array

As `date_parse`, for `timelib_parse_from_format`.

echo date_parse_from_format("Y-m-d", "2024-05-06")["day"];   // => 6

# date_get_last_errors

date_get_last_errors(): array|false

The warnings and errors of the last date parse that had any, or `false`.

date_create("2024-02-30"); echo date_get_last_errors()["warning_count"];   // => 1

# timezone_open

timezone_open(string $timezone): DateTimeZone|false

`new DateTimeZone($timezone)`, except that an unknown zone warns and returns `false`. DIVERGENCE: only fixed-offset identifiers resolve (no tz database).

echo timezone_open("-0330")->getName();   // => -03:30

# timezone_name_get

timezone_name_get(DateTimeZone $object): string

`$object->getName()`.

echo timezone_name_get(timezone_open("EST"));   // => EST

# timezone_offset_get

timezone_offset_get(DateTimeZone $object, DateTimeInterface $datetime): int

The zone's offset from UTC in seconds at `$datetime`.

echo timezone_offset_get(timezone_open("+01:00"), date_create("@0"));   // => 3600

By-reference array mutators

# array_pop

array_pop(array $array): mixed

Removes and returns the LAST element, shortening the caller's array in place. An empty array yields null.

$a = [1, 2, 3]; echo array_pop($a), count($a);   // => 32

# array_shift

array_shift(array $array): mixed

Removes and returns the FIRST element, reindexing the remaining integer keys from 0. An empty array yields null.

$a = [1, 2, 3]; echo array_shift($a), implode(",", $a);   // => 12,3

# array_unshift

array_unshift(array $array, mixed ...$values): int

Prepends the values, reindexing integer keys from 0, and returns the new element count.

$a = [2, 3]; array_unshift($a, 1); echo implode(",", $a);   // => 1,2,3

# array_splice

array_splice(array $array, int $offset, ?int $length = null, mixed $replacement = []): array

Removes a run of elements in place and optionally substitutes a replacement, returning the extracted run. Negative offsets and lengths count from the end.

$a = [1, 2, 3, 4]; array_splice($a, 1, 2); echo implode(",", $a);   // => 1,4

Built-in object methods

# Generator::current

$generator->current(): mixed

The value the generator is currently suspended on, running it up to its first `yield` if it has not started. Generator bodies run on their own native stack, so a `yield` deep inside nested calls suspends the whole VM in one stack switch.

function g() { yield 1; yield 2; } $x = g(); echo $x->current();   // => 1

# Generator::key

$generator->key(): mixed

The key of the current element — the auto-incrementing integer for a bare `yield`, or the explicit key from a `yield $k => $v`.

function g() { yield "k" => "v"; } $x = g(); echo $x->key();   // => k

# Generator::next

$generator->next(): void

Resumes the generator until its next `yield` or its return. Equivalent to `send(null)` with the result discarded.

function g() { yield 1; yield 2; } $x = g(); $x->next(); echo $x->current();   // => 2

# Generator::valid

$generator->valid(): bool

False once the body has run to completion, which is what ends a `foreach` over the generator.

function g() { yield 1; } $x = g(); $x->next(); var_dump($x->valid());   // => bool(false)

# Generator::rewind

$generator->rewind(): void

Runs the generator up to its first `yield` if it has not started. It cannot actually rewind an already-advanced generator, matching PHP.

# Generator::send

$generator->send(mixed $value): mixed

Resumes the generator, making the suspended `yield` expression evaluate to `$value`, and returns the next yielded value. A missing argument sends null.

function g() { $a = yield 1; echo "got:$a"; }
$x = g(); echo $x->current(); $x->send("Z");   // => 1got:Z

# Generator::throw

$generator->throw(object $exception): mixed

Resumes the generator by raising the exception AT the suspended `yield`, so a `try`/`catch` inside the body can handle it.

function g() { try { yield 1; } catch (Exception $e) { echo "C:" . $e->getMessage(); } }
$x = g(); $x->current(); $x->throw(new Exception("boom"));   // => C:boom

# Generator::getReturn

$generator->getReturn(): mixed

The value the generator body returned. It reads the stored slot directly and does NOT raise when the generator has not finished — it simply reports whatever is there, which differs from PHP's `Exception`.

function g() { yield 1; return 9; } $x = g(); $x->next(); echo $x->getReturn();   // => 9

# Closure::bind

Closure::bind(Closure $closure, ?object $newThis, object|string|null $newScope = null): Closure

Static form of `bindTo`: returns a copy of the closure with `$this` rebound and, when a scope is given, private-member access granted for that class.

class C { private $p = 7; }
$f = function () { return $this->p; };
echo Closure::bind($f, new C, C::class)();   // => 7

# Closure::fromCallable

Closure::fromCallable(callable $callback): Closure

Builds a real `Closure` over the callable — a variadic forwarder holding it, so `instanceof Closure` and `get_class()` both answer `Closure` and the arguments reach the callable by name as well as by position. A `Closure` argument is handed straight back rather than wrapped again. Anything that names nothing invocable is `TypeError: Failed to create closure from callable: …`, whose reason clause is the one a `callable` library parameter quotes.

$c = Closure::fromCallable("strlen"); echo $c("abcd");   // => 4

# Closure::bindTo

$closure->bindTo(?object $newThis, object|string|null $newScope = null): Closure

Returns a copy of the closure with `$this` rebound. Both arguments are optional; omitting the object unbinds `$this`.

class C { public $p = 3; }
$f = function () { return $this->p; };
echo $f->bindTo(new C)();   // => 3

# Closure::call

$closure->call(object $newThis, mixed ...$args): mixed

Binds and invokes in one step. The scope is ALWAYS the bound object's own class, so the closure can reach that class's private members without naming a scope.

class C { private $p = 8; }
$f = function () { return $this->p; };
echo $f->call(new C);   // => 8

# enum::cases

EnumName::cases(): array

A list of every case object of the enum, in declaration order. Synthesized per enum rather than declared, so it exists on both pure and backed enums.

enum S: string { case A = "a"; case B = "b"; } echo count(S::cases());   // => 2

# enum::from

EnumName::from(string|int $value): EnumName

The case whose backing value equals the argument. An unmatched value is an error — use `tryFrom` for the null-returning form.

enum S: string { case A = "a"; } echo S::from("a")->name;   // => A

# enum::tryFrom

EnumName::tryFrom(string|int $value): ?EnumName

The case whose backing value equals the argument, or null when none matches. It shares `from`'s implementation with the error path turned into a null return.

enum S: string { case A = "a"; } var_dump(S::tryFrom("z"));   // => NULL

# enum->name

$case->name: string

The declared case name, present on every enum case — pure and backed alike.

enum S { case A; } echo S::A->name;   // => A

# enum->value

$case->value: string|int

The backing value of a case. Present only on a backed enum (one declared with a `: string` or `: int` backing type); a pure enum's cases carry only `name`.

enum S: string { case A = "a"; } echo S::A->value;   // => a

Filesystem

# file_get_contents

file_get_contents(string $filename): string|false

Reads the file's bytes and returns them as a string, or `false` on any I/O error with no warning. `$offset` counts from the start (from the end when negative) and `$length` caps what follows; a negative `$length` is a `ValueError`. DIVERGENCE: `$use_include_path` and `$context` are never read.

file_put_contents("/tmp/php_ref.txt", "hi"); echo file_get_contents("/tmp/php_ref.txt");   // => hi

# file_put_contents

file_put_contents(string $filename, mixed $data, int $flags = 0): int|false

Writes the data — an array is string-cast element-wise and concatenated with no separator — and returns the byte count. Only `FILE_APPEND` is honoured; `LOCK_EX` and `FILE_USE_INCLUDE_PATH` are accepted and ignored, so no locking happens.

echo file_put_contents("/tmp/php_ref.txt", "abc");   // => 3

# file

file(string $filename, int $flags = 0): array|false

Splits the file on `\n`, keeping each terminator by default. `FILE_IGNORE_NEW_LINES` and `FILE_SKIP_EMPTY_LINES` are honoured; `FILE_USE_INCLUDE_PATH` is ignored. A read failure returns `false`.

file_put_contents("/tmp/php_ref.txt", "a\nb");
echo count(file("/tmp/php_ref.txt", FILE_IGNORE_NEW_LINES));   // => 2

# readfile

readfile(string $filename): int|false

Writes the file's bytes to output and returns how many there were. `$use_include_path` and `$context` are not read.

file_put_contents("/tmp/php_ref.txt", "hi"); echo readfile("/tmp/php_ref.txt");   // => hi2

# file_exists

file_exists(string $filename): bool

Stats the path, following symlinks, so a broken symlink reports false. There is no stat cache to invalidate.

var_dump(file_exists("/"));   // => bool(true)

# is_file

is_file(string $filename): bool

True when the path stats to a regular file, following symlinks. A failed stat is false.

var_dump(is_file("/"));   // => bool(false)

# is_dir

is_dir(string $filename): bool

True when the path stats to a directory, following symlinks.

var_dump(is_dir("/"));   // => bool(true)

# is_link

is_link(string $filename): bool

True when an `lstat` reports a symlink; the link is not followed.

var_dump(is_link("/"));   // => bool(false)

# is_readable

is_readable(string $filename): bool

DIVERGENCE: it does NOT call `access(2)` with `R_OK` — it only checks that the path can be stat'd. A file that exists but cannot be opened by the current user still reports true.

var_dump(is_readable("/"));   // => bool(true)

# is_writable

is_writable(string $filename): bool

DIVERGENCE: no `access(2)` call. It stats the path and reports the inverse of the read-only mode bit, so it ignores the effective uid and gid, ACLs, and read-only mounts. A missing path is false.

# is_writeable

is_writeable(string $filename): bool

The alias of `is_writable`, sharing its match arm and its mode-bits-only limitation.

# is_executable

is_executable(string $filename): bool

A REAL `access(2)` check with `X_OK` for the current user — the one predicate in this module that consults the effective credentials. A path containing an interior NUL, or a missing path, is false.

# filetype

filetype(string $filename): string|false

One of `dir`, `file`, `link`, `fifo`, `char`, `block`, `socket`, or `unknown`. It uses `lstat`, so a symlink reports `link` rather than its target's type. A failed stat returns `false`.

echo filetype("/");   // => dir

# filesize

filesize(string $filename): int|false

The file's size in bytes from a real stat, following symlinks. A failed stat returns `false`.

file_put_contents("/tmp/php_ref.txt", "abc"); echo filesize("/tmp/php_ref.txt");   // => 3

# filemtime

filemtime(string $filename): int|false

The modification time truncated to whole Unix seconds. Any failure returns `false` — including a pre-1970 mtime, which cannot be represented by the underlying duration.

# fileperms

fileperms(string $filename): int|false

The full `st_mode`, file-type bits included rather than just the permission bits — mask with `0777` to get what `chmod` would take. A failed stat returns `false`.

# stat

stat(string $filename): array|false

A real `stat(2)`, following symlinks. Returns the full 26-entry PHP array: the 13 fields `dev ino mode nlink uid gid rdev size atime mtime ctime blksize blocks` under numeric keys `0`-`12`, then the same values again under their names. No field is synthesized.

echo count(stat("/"));   // => 26

# lstat

lstat(string $filename): array|false

The same 26-entry array as `stat`, built from an `lstat` so it describes the symlink itself rather than its target.

echo count(lstat("/"));   // => 26

# clearstatcache

clearstatcache(bool $clear_realpath_cache = false, string $filename = ""): null

A no-op returning null. There is no stat cache in this implementation, so nothing is invalidated and neither argument is read.

var_dump(clearstatcache());   // => NULL

# unlink

unlink(string $filename): bool

Removes a file. Returns `false` on any error, including an attempt to remove a directory. `$context` is not read.

# mkdir

mkdir(string $directory, int $permissions = 0777, bool $recursive = false): bool

Creates a directory. `$recursive` is honoured and selects the create-all path. DIVERGENCE: `$permissions` is accepted and IGNORED — no mode is applied, so the directory gets the process umask default.

# rmdir

rmdir(string $directory): bool

Removes an empty directory. It is never recursive, so a non-empty directory returns `false`.

# rename

rename(string $from, string $to): bool

Renames a path with same-filesystem semantics. Errors return `false` silently.

# copy

copy(string $from, string $to): bool

Copies the source over the destination, creating or truncating it and carrying the permission bits. Symlinks are followed.

# touch

touch(string $filename, ?int $mtime = null): bool

Creates the file if absent — without truncating an existing one — and sets its modification time, defaulting to now. DIVERGENCE: PHP's third `$atime` argument is accepted positionally but never applied, because the underlying file handle exposes only the modification time.

# scandir

scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING): array|false

Lists a directory, SYNTHESIZING the `.` and `..` entries rather than reading them, then sorting by Rust byte order (not PHP's locale collation). Only the descending order is recognized; `SCANDIR_SORT_NONE` is not, so the result is always sorted. A read failure returns `false`.

var_dump(in_array(".", scandir("/tmp")));   // => bool(true)

# glob

glob(string $pattern, int $flags = 0): array

The pattern splits at its LAST `/`: everything before is a literal directory, so wildcards never expand across directory levels. The name part is matched with the same rules as `fnmatch` (`*`, `?`, `[…]`, `[:class:]`, backslash escapes). NOT supported: `{a,b}` brace expansion. `GLOB_ONLYDIR`, `GLOB_MARK`, and `GLOB_NOSORT` are honoured. Dotfiles are skipped unless the name pattern itself starts with `.`. DIVERGENCE: it never returns `false` — an unreadable directory yields an empty array.

file_put_contents("/tmp/php_ref_g.txt", ""); echo count(glob("/tmp/php_ref_g.*"));   // => 1

# fnmatch

fnmatch(string $pattern, string $filename, int $flags = 0): bool

A port of the reference libc matcher over the whole string: `*`, `?`, `[…]` ranges, `!`/`^` negation, `[:class:]` names and backslash escapes. `FNM_NOESCAPE`, `FNM_PATHNAME`, `FNM_PERIOD` and `FNM_CASEFOLD` are all honoured (case folding is ASCII-only). A trailing backslash matches nothing; an unterminated bracket follows the platform libc (a literal `[` with glibc on Linux, no match on macOS).

var_dump(fnmatch("*.txt", "a.txt"));   // => bool(true)

# basename

basename(string $path, string $suffix = ""): string

A pure string operation with no filesystem access: it strips all trailing `/`, then takes the text after the last remaining one. The suffix is removed only when doing so would not empty the result, so `basename("foo.txt", "foo.txt")` returns `foo.txt` unchanged. Windows `\` separators are not recognized.

echo basename("/a/b/c.txt", ".txt");   // => c

# dirname

dirname(string $path, int $levels = 1): string

Applies the one-level dirname `$levels` times. DIVERGENCE: a `$levels` of 0 or negative is clamped to 1 rather than raising `ValueError`. An all-slash path yields `/`, a path with no `/` yields `.`, and the empty string stays empty.

echo dirname("/a/b/c.txt"), "|", dirname("/a/b/c.txt", 2);   // => /a/b|/a

# pathinfo

pathinfo(string $path, int $flags = PATHINFO_ALL): array|string

Splits the basename at the LAST `.`, matching PHP's own `php_pathinfo`, so `.htaccess` gives extension `htaccess` and an empty filename. With no second argument it returns a map whose `dirname` key is omitted when the directory part is empty and whose `extension` key is OMITTED ENTIRELY when the basename has no dot. With a selector it returns one string, or `""` when that piece is absent. No filesystem access.

echo pathinfo("/a/b.txt", PATHINFO_EXTENSION);   // => txt

# realpath

realpath(string $path): string|false

Canonicalizes the path, resolving symlinks and `.`/`..` to an absolute path. The path must EXIST — a non-existent name under an existing parent returns `false`. Being the OS call, on macOS it returns the `/private`-prefixed form for `/tmp` and `/var`.

var_dump(realpath("/no/such/path"));   // => bool(false)

# getcwd

getcwd(): string|false

The current working directory, or `false` when the syscall fails — for instance after the directory has been removed.

var_dump(strlen(getcwd()) > 0);   // => bool(true)

# sys_get_temp_dir

sys_get_temp_dir(): string

The temporary directory, honouring `TMPDIR` and otherwise `/tmp`, with trailing slashes trimmed. It never returns `false`.

var_dump(strlen(sys_get_temp_dir()) > 0);   // => bool(true)

# tempnam

tempnam(string $directory, string $prefix): string|false

Creates a new empty file and returns its path, falling back to the system temp directory when `$directory` is not one. DIVERGENCE: uniqueness comes from the process id plus a nanosecond timestamp rather than randomness, and although the file is created exclusively it is NOT chmod'ed to 0600 — it gets the default mode masked by the umask, so do not treat it as private.

# disk_free_space

disk_free_space(string $directory): float|false

A real `statvfs(2)`, reporting the space available to an UNPRIVILEGED process (the available-blocks count, not the free-blocks count). A failed call returns `false`.

var_dump(disk_free_space("/") > 0);   // => bool(true)

# diskfreespace

diskfreespace(string $directory): float|false

The alias of `disk_free_space`, sharing its match arm.

# disk_total_space

disk_total_space(string $directory): float|false

A real `statvfs(2)` reporting the filesystem's total size in bytes.

var_dump(disk_total_space("/") > 0);   // => bool(true)

File streams

# fopen

fopen(string $filename, string $mode, bool $use_include_path = false, ?resource $context = null): resource|false

Opens a plain file or one of the `php://` wrappers: `memory`, `temp` (and `temp/maxmemory:N`), `stdin`, `stdout`, `stderr`, `output`. `r` is read-only and `w`/`a`/`x`/`c` write-only unless `+` is given; a read from a write-only file or a write to a read-only one fails with the reference's `errno=9 Bad file descriptor` notice. `a` writes at the end whatever the cursor says while `ftell` counts from 0, as `O_APPEND` does. A missing file, a directory opened for writing, an existing path under `x`, an unknown mode and an unknown `php://` wrapper each warn `Failed to open stream: …` and return `false`; an empty path is a `ValueError`. `php://memory` and `php://temp` are read-only only in a pure `r` mode. `$use_include_path` and `$context` are accepted and ignored.

$f = fopen("php://memory", "w+"); fwrite($f, "abc"); rewind($f); echo fread($f, 10);   // => abc

# tmpfile

tmpfile(): resource|false

A read/write stream that disappears when closed. DIVERGENCE: it is held in memory rather than in a file under the system temporary directory, which is observable only through `fstat`, where it reports as a memory stream.

$t = tmpfile(); fwrite($t, "hi"); rewind($t); echo fread($t, 2);   // => hi

# readline

readline(?string $prompt = null): string|false

One line of standard input without its newline, or `false` once input is exhausted. Reads the source directly rather than through `STDIN`'s buffer. The prompt is written only when standard input is a terminal, as libedit does; there is no line editing or history.

$line = readline();   // stdin "hi\n" => "hi"

# fread

fread(resource $stream, int $length): string|false

Copies up to `$length` bytes from the cursor and advances it. A read that gets fewer bytes than asked for sets end-of-file. A `$length` below 1 is a `ValueError`.

file_put_contents("/tmp/php_ref_s.txt", "abcdef");
$f = fopen("/tmp/php_ref_s.txt", "r"); echo fread($f, 3); fclose($f);   // => abc

# fgetcsv

fgetcsv(resource $stream, ?int $length = null, string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array|false

Reads a line (at most `$length` bytes) and parses it as `str_getcsv` does, reading further lines while an enclosed field is still open. A blank line is `[null]`; nothing left is `false`. Omitting `$escape` is deprecated.

$f = fopen("php://memory", "w+"); fwrite($f, "a,\"b\nc\"\n"); rewind($f); echo json_encode(fgetcsv($f, null, ",", "\"", ""));   // => ["a","b\nc"]

# fputcsv

fputcsv(resource $stream, array $fields, string $separator = ",", string $enclosure = "\"", string $escape = "\\", string $eol = "\n"): int|false

Writes the fields as one CSV line ended by `$eol`, enclosing a field that holds the separator, the enclosure, the escape, a space, a tab or a line break, and doubling an enclosure inside it unless the escape precedes it. Returns the bytes written. Omitting `$escape` is deprecated.

$f = fopen("php://memory", "w+"); fputcsv($f, ["a b", 1], ",", "\"", ""); rewind($f); echo stream_get_contents($f);   // => "a b",1

# fgets

fgets(resource $stream, ?int $length = null): string|false

Reads from the cursor through the next `\n` inclusive. A `$length` caps the read at one byte fewer, and one below 1 is a `ValueError`. Nothing left returns `false`; running out before a newline sets end-of-file.

file_put_contents("/tmp/php_ref_s.txt", "a\nb");
$f = fopen("/tmp/php_ref_s.txt", "r"); echo trim(fgets($f)); fclose($f);   // => a

# fgetc

fgetc(resource $stream): string|false

One byte from the cursor, or `false` (and end-of-file) when none is left.

$f = fopen("php://memory", "w+"); fwrite($f, "xy"); rewind($f); echo fgetc($f);   // => x

# fwrite

fwrite(resource $stream, string $data, ?int $length = null): int|false

Writes at the cursor, zero-filling a gap left by seeking past the end. A plain file is then rewritten whole on disk at once. `STDOUT` and `php://stdout` go straight to standard output past any output buffering, `php://output` goes through it like `echo`, and `STDERR`/`php://stderr` to standard error. `$length` truncates the data. A read-only stream returns `false`.

$f = fopen("php://memory", "w+"); echo fwrite($f, "abc");   // => 3

# fputs

fputs(resource $stream, string $data, ?int $length = null): int|false

The alias of `fwrite`, sharing its match arm.

# fclose

fclose(resource $stream): bool

Flushes a dirty file and closes the stream. The value stays a resource of type `Unknown`: `var_dump` shows `resource(N) of type (Unknown)` and `gettype` says `resource (closed)`.

$f = fopen("php://memory", "r"); fclose($f); var_dump($f);   // => resource(5) of type (Unknown)

# fflush

fflush(resource $stream): bool

Rewrites a dirty file's buffer to disk. Returns true for any open stream.

# feof

feof(resource $stream): bool

True once a read has wanted more than the stream had — NOT merely when the cursor sits at the end, so reading exactly the remaining bytes leaves it false. A seek clears it.

file_put_contents("/tmp/php_ref_s.txt", "a");
$f = fopen("/tmp/php_ref_s.txt", "r"); fread($f, 1); var_dump(feof($f)); fgetc($f); var_dump(feof($f)); fclose($f);   // => bool(false) bool(true)

# ftell

ftell(resource $stream): int|false

The current cursor position.

file_put_contents("/tmp/php_ref_s.txt", "abc");
$f = fopen("/tmp/php_ref_s.txt", "r"); fread($f, 2); echo ftell($f); fclose($f);   // => 2

# fseek

fseek(resource $stream, int $offset, int $whence = SEEK_SET): int

Repositions the cursor from the start, the current position (`SEEK_CUR`) or the end (`SEEK_END`). A target before the start returns -1 and leaves the cursor alone; past the end is allowed, and a write there zero-fills the gap. Returns 0 on success.

file_put_contents("/tmp/php_ref_s.txt", "abcdef");
$f = fopen("/tmp/php_ref_s.txt", "r"); fseek($f, 3); echo fread($f, 2); fclose($f);   // => de

# rewind

rewind(resource $stream): bool

Seeks the cursor to 0 and clears end-of-file.

file_put_contents("/tmp/php_ref_s.txt", "abc");
$f = fopen("/tmp/php_ref_s.txt", "r"); fread($f, 2); rewind($f); echo fread($f, 1); fclose($f);   // => a

# ftruncate

ftruncate(resource $stream, int $size): bool

Cuts the stream to `$size` bytes or extends it with NULs, without moving the cursor. A read-only stream returns `false`; a negative size is a `ValueError`.

$f = fopen("php://memory", "w+"); fwrite($f, "hello"); ftruncate($f, 2); rewind($f); echo fread($f, 10);   // => he

# fstat

fstat(resource $stream): array|false

The 26-entry `stat` array. A plain file and a standard stream report the real `stat(2)` of what they are attached to; a memory or temp stream reports the reference's fabricated one — device `12`, mode `33206` (`33060` when read-only), its size, and `-1` for `rdev`/`blksize`/`blocks`. `php://output` returns `false`.

$f = fopen("php://memory", "w+"); fwrite($f, "abc"); echo fstat($f)["size"];   // => 3

# stream_get_contents

stream_get_contents(resource $stream, ?int $length = null, int $offset = -1): string|false

Everything from the cursor, or at most `$length` bytes, after first seeking to `$offset` when it is 0 or more.

$f = fopen("php://memory", "w+"); fwrite($f, "hello world"); echo stream_get_contents($f, 5, 6);   // => world

# fpassthru

fpassthru(resource $stream): int

Writes everything from the cursor to the output (through output buffering) and returns the byte count.

$f = fopen("php://memory", "w+"); fwrite($f, "hi"); rewind($f); fpassthru($f);   // => hi

# is_resource

is_resource(mixed $value): bool

True only for an OPEN stream resource — a closed handle reports false, as in PHP.

$f = fopen("/tmp/php_ref_s.txt", "w"); fclose($f); var_dump(is_resource($f));   // => bool(false)

# get_resource_type

get_resource_type(resource $resource): string

`stream` for an open stream and `Unknown` for a closed one — streams are the only resource kind this runtime has.

$f = fopen("php://memory", "r"); echo get_resource_type($f);   // => stream

# get_resource_id

get_resource_id(resource $resource): int

The resource number — the `N` of `resource(N)` and of `Resource id #N` — open or closed.

echo get_resource_id(STDERR);   // => 3

Misc

# array_find

array_find(array $array, callable $callback): mixed

The PHP 8.4 search: returns the first VALUE for which `$callback($value, $key)` is truthy — note the value comes first. No match returns null, which is indistinguishable from having matched a null element.

echo array_find([1, 8, 3], fn($v, $k) => $v > 5);   // => 8

# array_find_key

array_find_key(array $array, callable $callback): mixed

The KEY of the first element for which `$callback($value, $key)` is truthy, or null when none matches. It shares `array_find`'s loop.

echo array_find_key([1, 8, 3], fn($v, $k) => $v > 5);   // => 1

# array_any

array_any(array $array, callable $callback): bool

True as soon as `$callback($value, $key)` is truthy for some element; false for an empty array.

var_dump(array_any([1, 2], fn($v, $k) => $v > 1));   // => bool(true)

# array_all

array_all(array $array, callable $callback): bool

True when `$callback($value, $key)` is truthy for every element, and true for an empty array.

var_dump(array_all([2, 4], fn($v, $k) => $v % 2 === 0));   // => bool(true)

# array_udiff

array_udiff(array $array1, array $array2, ..., callable $value_compare_func): array

Keeps the entries of the first array whose VALUE compares non-zero against every value of every other array, preserving keys. The comparator is the LAST argument and any number of operand arrays may precede it. Ported from `php_array_diff`: every operand is `zend_sort`ed with the comparator and the sorted lists are walked in step, so the callback sees exactly the reference's pairs.

echo implode(",", array_udiff([1, 2, 3], [2], fn($a, $b) => $a <=> $b));   // => 1,3

# array_uintersect

array_uintersect(array $array1, array $array2, ..., callable $value_compare_func): array

Keeps the entries of the first array whose value compares equal to some value in EVERY other array, preserving keys. Same comparator-last shape and sort-then-walk port (`php_array_intersect`) as `array_udiff`.

echo implode(",", array_uintersect([1, 2, 3], [2, 3], fn($a, $b) => $a <=> $b));   // => 2,3

# array_diff_ukey

array_diff_ukey(array $array1, array $array2, ..., callable $key_compare_func): array

The key-comparing counterpart of `array_udiff`: an entry survives when its KEY compares non-zero against every key of every other array.

echo implode(",", array_diff_ukey(["a" => 1, "b" => 2], ["a" => 9], fn($x, $y) => strcmp($x, $y)));   // => 2

# array_intersect_ukey

array_intersect_ukey(array $array1, array $array2, ..., callable $key_compare_func): array

Keeps the entries of the first array whose key compares equal to some key in every other array, using the caller's comparator.

echo implode(",", array_intersect_ukey(["a" => 1, "b" => 2], ["a" => 9], fn($x, $y) => strcmp($x, $y)));   // => 1

# array_diff_uassoc

array_diff_uassoc(array $array, array ...$arrays, callable $key_compare_func): array

Keeps the entries of the first array whose KEY (compared by the callback) and VALUE (compared as strings) do not both match an entry of any other array.

echo implode(",", array_diff_uassoc(["a" => 1, "b" => 2], ["a" => 1, "b" => 3], "strcmp"));   // => 2

# array_intersect_uassoc

array_intersect_uassoc(array $array, array ...$arrays, callable $key_compare_func): array

Keeps the entries of the first array whose key (compared by the callback) and value (compared as strings) match an entry of every other array.

echo implode(",", array_intersect_uassoc(["a" => 1, "b" => 2], ["a" => 1, "b" => 3], "strcmp"));   // => 1

# array_udiff_assoc

array_udiff_assoc(array $array, array ...$arrays, callable $value_compare_func): array

Keeps the entries of the first array that no other array holds under the same key with a value the callback calls equal. Keys are matched by lookup, not by callback.

echo implode(",", array_udiff_assoc(["a" => 1, "b" => 2], ["a" => 1, "b" => 3], fn($x, $y) => $x <=> $y));   // => 2

# array_uintersect_assoc

array_uintersect_assoc(array $array, array ...$arrays, callable $value_compare_func): array

Keeps the entries of the first array that every other array holds under the same key with a value the callback calls equal.

echo implode(",", array_uintersect_assoc(["a" => 1, "b" => 2], ["a" => 1, "b" => 3], fn($x, $y) => $x <=> $y));   // => 1

# array_udiff_uassoc

array_udiff_uassoc(array $array, array ...$arrays, callable $value_compare_func, callable $key_compare_func): array

`array_diff_uassoc` with the values compared by the first callback as well; the key callback comes last.

echo implode(",", array_udiff_uassoc(["a" => 1, "b" => 2], ["a" => 1, "b" => 3], fn($x, $y) => $x <=> $y, "strcmp"));   // => 2

# array_uintersect_uassoc

array_uintersect_uassoc(array $array, array ...$arrays, callable $value_compare_func, callable $key_compare_func): array

`array_intersect_uassoc` with the values compared by the first callback as well; the key callback comes last.

echo implode(",", array_uintersect_uassoc(["a" => 1, "b" => 2], ["a" => 1, "b" => 3], fn($x, $y) => $x <=> $y, "strcmp"));   // => 1

# array_multisort

array_multisort(array $array1, mixed ...$rest): bool

Fully variadic: every array argument starts a new column and every scalar applies as a flag to the most recent column. Columns break ties left to right, and every column is reordered by the same permutation, reindexed from 0 with all keys discarded. Only `SORT_ASC`, `SORT_DESC`, `SORT_REGULAR`, `SORT_NUMERIC`, and `SORT_STRING` are recognized — `SORT_NATURAL`, `SORT_FLAG_CASE`, and any OR-combination are silently ignored. It returns `false` rather than raising when there is no array argument or the columns differ in length.

$a = [3, 1, 2]; $b = ["c", "a", "b"]; array_multisort($a, $b);
echo implode(",", $a), "|", implode(",", $b);   // => 1,2,3|a,b,c

# array_walk_recursive

array_walk_recursive(array $array, callable $callback, mixed $arg = null): bool

Descends nested arrays and invokes `$callback($value, $key[, $arg])` on non-array LEAVES only — a nested array is recursed into but never passed to the callback. The leaf goes in through a reference cell, so a `function (&$v)` callback rewrites it in place, exactly as with `array_walk`.

$a = [1, [2, 3]]; array_walk_recursive($a, function ($v, $k) { echo $v; });   // => 123

# str_word_count

str_word_count(string $string, int $format = 0, ?string $characters = null): int|array

Format 1 returns the words, format 2 a byte-offset-to-word map, and 0 the count; any other value raises `ValueError: str_word_count(): Argument #2 ($format) must be a valid format value`. A word is a run of ASCII letters plus `'` and `-`, which are ALWAYS word characters; `$characters` only ADDS bytes to that set and can never restrict it. Matching is bytewise, so multibyte text is not recognized as words.

echo str_word_count("a b c");   // => 3

# strnatcmp

strnatcmp(string $string1, string $string2): int

A byte-for-byte port of PHP's natural-order comparison, returning only the sign. Leading zeros are stripped ONCE at the start of each string rather than per digit run, so `strnatcmp("1", "01")` is 0. A digit run compares left-aligned when either side starts with `0`, and by magnitude otherwise.

echo strnatcmp("img12", "img2");   // => 1

# strnatcasecmp

strnatcasecmp(string $string1, string $string2): int

`strnatcmp` with ASCII case folding, returning only the sign. Non-ASCII bytes are compared unfolded.

echo strnatcasecmp("IMG2", "img2");   // => 0

# soundex

soundex(string $string): string

The real Soundex algorithm, ported from PHP's own `soundex.c`: the first letter verbatim, then up to three consonant codes, right-padded with zeros. ASCII-only — a string with no ASCII letters returns `"0000"`.

echo soundex("Robert");   // => R163

# metaphone

metaphone(string $string, int $max_phonemes = 0): string

The real traditional Metaphone, ported from PHP's `metaphone.c` including the special first-phoneme cases and the CH, TH, DG, GH, and TIO/TIA rules — so `TH` encodes as the DIGIT zero and `CH` as `X`, as in PHP. ASCII-only; a letterless input returns the empty string. `$max_phonemes` caps the length, with 0 or negative meaning unlimited.

echo metaphone("Thompson");   // => 0MPSN

# str_getcsv

str_getcsv(string $string, string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array

A port of `php_fgetcsv`: doubled enclosures inside an enclosed field are literals, the escape character keeps itself and the byte after it, whatever follows a closing enclosure up to the separator joins the field, unenclosed fields keep their blanks but lose a trailing line end, and an embedded newline stays in an enclosed field. An empty input is `[null]`. A separator or enclosure that is not one byte, or an escape longer than one, is a `ValueError`; omitting `$escape` raises PHP 8.4's deprecation.

print_r(str_getcsv("a,b"));   // => Array\n(\n    [0] => a\n    [1] => b\n)

# ip2long

ip2long(string $ip): int|false

A dotted-quad IPv4 address as an integer, parsed by the platform's `inet_pton`; false for anything else. A NUL byte is a `ValueError`.

echo ip2long("192.168.1.1");   // => 3232235777

# long2ip

long2ip(int $ip): string

The low 32 bits of `$ip` as a dotted quad.

echo long2ip(3232235777);   // => 192.168.1.1

# strcoll

strcoll(string $string1, string $string2): int

Locale-aware comparison under the current `LC_COLLATE`: the C library's `strcoll`, its raw result returned.

var_dump(strcoll("a", "b") < 0);   // => bool(true)

# version_compare

version_compare(string $version1, string $version2, ?string $operator = null): int|bool

Compares two PHP-standardized version strings: `-`, `_` and `+` become `.`, a `.` is inserted between digit and non-digit runs, and components compare numerically or by special-form rank (`dev` < `alpha`/`a` < `beta`/`b` < `RC`/`rc` < number < `pl`/`p`). Without `$operator` returns -1, 0 or 1; with one (`<`/`lt`, `<=`/`le`, `>`/`gt`, `>=`/`ge`, `==`/`eq`, `!=`/`<>`/`ne`) returns whether it holds.

var_dump(version_compare("8.5.0RC1", "8.5.0", "<"));   // => bool(true)

# uniqid

uniqid(string $prefix = "", bool $more_entropy = false): string

A hex timestamp of the form `%08x%05x` from the wall clock's seconds and microseconds, prefixed by `$prefix`. `$more_entropy` is honoured and appends a fractional suffix of PHP's shape, but with only 1000 distinct values. DIVERGENCE: the clock is the ONLY entropy source — there is no RNG, no counter, and no collision avoidance, so two calls in the same microsecond return IDENTICAL strings. It is not suitable as a unique identifier under load.

var_dump(strlen(uniqid()) === 13);   // => bool(true)

# pack

pack(string $format, mixed ...$values): string

A port of ext/standard/pack.c: every format code (`a A Z h H c C s S n v i I l L N V q Q J P f g G d e E x X @`), repeat counts and `*`, and its warnings and `ValueError`s. The result is the packed bytes.

echo bin2hex(pack("nv", 0x1234, 0x1234));   // => 12343412

# unpack

unpack(string $format, string $string, int $offset = 0): array|false

A port of ext/standard/pack.c's `unpack`: `code[repeat]name` items separated by `/`, numbered keys for a repeat, and its warnings for short input. It reads the string's bytes, as `ord` does.

print_r(unpack("nbig/C2c", "\x12\x34AB"));   // => Array ( [big] => 4660 [c1] => 65 [c2] => 66 )

Output buffering

# ob_start

ob_start(?callable $callback = null, int $chunk_size = 0, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS): bool

Pushes an output handler. `$callback($buffer, $phase)` rewrites the buffer whenever it is flushed, cleaned or removed (its `false` passes the buffer through and disables it; `true` or `""` swallows it); a non-zero `$chunk_size` runs it whenever the buffer reaches that size; `$flags` choose whether it may be cleaned, flushed or removed. An invalid callback warns, notices `Failed to create buffer` and returns false.

ob_start(fn($b) => strtoupper($b)); echo "hi"; ob_end_flush();   // => HI

# ob_get_contents

ob_get_contents(): string|false

The top buffer's contents WITHOUT popping it, or `false` when no buffer is active.

ob_start(); echo "ab"; $s = ob_get_contents(); ob_end_clean(); echo $s;   // => ab

# ob_get_clean

ob_get_clean(): string|false

Returns the top buffer and removes it, running its handler with `FINAL|CLEAN` and discarding what that returns. `false`, silently, when no buffer is active.

ob_start(); echo "x"; echo ob_get_clean();   // => x

# ob_end_clean

ob_end_clean(): bool

Removes the top buffer, running its handler with `FINAL|CLEAN` and discarding the result. A notice and false when there is no buffer or it is not removable.

ob_start(); echo "gone"; var_dump(ob_end_clean());   // => bool(true)

# ob_end_flush

ob_end_flush(): bool

Removes the top buffer, passing what its handler returns (with `FINAL`) to the level below. A notice and false when there is no buffer or it is not removable.

ob_start(); echo "out"; ob_end_flush();   // => out

# ob_get_flush

ob_get_flush(): string|false

Returns the top buffer's contents, then does `ob_end_flush()`.

ob_start(); echo "y"; $s = ob_get_flush(); echo "|$s";   // => y|y

# ob_flush

ob_flush(): bool

Runs the top handler with `FLUSH` and passes its output to the level below, keeping the buffer. A notice and false when there is no buffer or it is not flushable.

ob_start(); echo "a"; ob_flush(); echo "b"; ob_end_clean();   // => a

# ob_get_level

ob_get_level(): int

The genuine nesting depth of the buffer stack.

ob_start(); $n = ob_get_level(); ob_end_clean(); echo $n;   // => 1

# ob_get_length

ob_get_length(): int|false

The top buffer's length in BYTES, not characters. `false` when no buffer is active.

ob_start(); echo "abc"; $n = ob_get_length(); ob_end_clean(); echo $n;   // => 3

# ob_clean

ob_clean(): bool

Runs the top handler with `CLEAN`, discards its result, and empties the buffer. A notice and false when there is no buffer or it is not cleanable.

ob_start(); echo "a"; ob_clean(); echo "b"; ob_end_flush();   // => b

# ob_list_handlers

ob_list_handlers(): array

The names of the active handlers, outermost first: `default output handler`, a function's name, `Class::method`, or a closure's `{closure:...}` name.

ob_start(); $l = ob_list_handlers(); ob_end_clean(); echo $l[0];   // => default output handler

# ob_get_status

ob_get_status(bool $full_status = false): array

The top handler's `name`, `type`, `flags`, `level`, `chunk_size`, `buffer_size` and `buffer_used`, or every handler's with `$full_status`; an empty array when none is active.

ob_start(); $s = ob_get_status(); ob_end_clean(); echo $s["name"];   // => default output handler

# ob_implicit_flush

ob_implicit_flush(bool $enable = true): void

Turns flushing after every write on or off; the CLI already writes immediately.

var_dump(ob_implicit_flush());   // => NULL

# flush

flush(): void

Flushes the SAPI's own output; the output-buffering stack is not touched.

var_dump(flush());   // => NULL

System and runtime environment

# getenv

getenv(?string $name = null, bool $local_only = false): string|array|false

Reads the REAL process environment. With no argument it returns every variable as an array; with a name, its value or `false`. The `$local_only` argument is accepted and ignored.

putenv("PHP_REF_X=1"); echo getenv("PHP_REF_X");   // => 1

# putenv

putenv(string $assignment): true

Mutates the REAL process environment, so the change is visible to `getenv` and to spawned children. `"K=V"` sets and a bare name unsets. It always returns true, never false.

putenv("PHP_REF_Y=2"); echo getenv("PHP_REF_Y");   // => 2

# getmypid

getmypid(): int

The real process id.

var_dump(getmypid() > 0);   // => bool(true)

# getmyuid

getmyuid(): int

DIVERGENCE: a stub that always returns 0. The real user id is not queried.

echo getmyuid();   // => 0

# getmygid

getmygid(): int

DIVERGENCE: a stub that always returns 0, sharing the `getmyuid` arm.

echo getmygid();   // => 0

# phpversion

phpversion(?string $extension = null): string|false

`PHP_VERSION`. DIVERGENCE: the `$extension` argument is never read, so a per-extension lookup returns the PHP version instead of the extension's or `false`.

var_dump(phpversion() === PHP_VERSION);   // => bool(true)

# php_sapi_name

php_sapi_name(): string

DIVERGENCE: always `"cli"`, however the runtime was entered — REPL, language server, or embedded.

echo php_sapi_name();   // => cli

# php_uname

php_uname(string $mode = "a"): string

Built from the COMPILE-TIME target OS, the architecture, and the `HOSTNAME` environment variable (falling back to `localhost`) — not from a real `uname(2)`. Modes `s`, `n`, `m`, and `a` work; DIVERGENCE: `r` (release) and `v` (version) both return the EMPTY STRING.

var_dump(php_uname("r") === "");   // => bool(true)

# memory_get_usage

memory_get_usage(bool $real_usage = false): int

DIVERGENCE: a fixed 2097152 (2 MiB). phplang has no PHP-level allocator to report, so this is a stable conventional value rather than a measurement.

echo memory_get_usage();   // => 2097152

# memory_get_peak_usage

memory_get_peak_usage(bool $real_usage = false): int

Shares the `memory_get_usage` arm, so peak and current are ALWAYS the same fixed 2097152.

echo memory_get_peak_usage();   // => 2097152

# gc_collect_cycles

gc_collect_cycles(): int

DIVERGENCE: a no-op that collects nothing and always returns 0.

echo gc_collect_cycles();   // => 0

# gc_mem_caches

gc_mem_caches(): int

DIVERGENCE: a no-op that frees nothing and always returns 0.

echo gc_mem_caches();   // => 0

# gc_enable

gc_enable(): bool

DIVERGENCE: there is no collector state to toggle. It returns true, where PHP returns void.

# gc_disable

gc_disable(): bool

DIVERGENCE: a no-op returning true, where PHP returns void.

# gc_enabled

gc_enabled(): bool

DIVERGENCE: always true, unaffected by any preceding `gc_disable()`.

gc_disable(); var_dump(gc_enabled());   // => bool(true)

# extension_loaded

extension_loaded(string $extension): bool

Checks a HARDCODED allow-list rather than what the standard library actually implements: `core`, `standard`, `json`, `pcre`, `mbstring`, `ctype`, `filter`, `date`, `hash`, `spl`, `tokenizer`. Everything else — `gmp` and `bcmath` included, though both are implemented — reports false.

var_dump(extension_loaded("json"), extension_loaded("gmp"));   // => bool(true) bool(false)

# sleep

sleep(int $seconds): int

DIVERGENCE: it does NOT sleep. The argument is never read and it returns 0 immediately, keeping the runtime responsive and tests deterministic.

echo sleep(3);   // => 0

# usleep

usleep(int $microseconds): null

DIVERGENCE: it does NOT sleep, returning null immediately.

var_dump(usleep(1000));   // => NULL

# time_nanosleep

time_nanosleep(int $seconds, int $nanoseconds): null

DIVERGENCE: it does NOT sleep, and it shares the `usleep` arm — so it returns null where PHP returns true on success.

var_dump(time_nanosleep(0, 1));   // => NULL

# sys_getloadavg

sys_getloadavg(): array

DIVERGENCE: always the fixed list `[0.0, 0.0, 0.0]`. No load average is queried.

echo implode(",", sys_getloadavg());   // => 0,0,0

# get_defined_constants

get_defined_constants(bool $categorize = false): array

A real snapshot of the host's constant table as a flat name-to-value map, including anything `define()` has added. `$categorize` is never read, so the nested by-extension form is unavailable.

define("PHP_REF_K", 5); echo get_defined_constants()["PHP_REF_K"];   // => 5

# php_ini_loaded_file

php_ini_loaded_file(): false

DIVERGENCE: always false — no php.ini is modeled.

var_dump(php_ini_loaded_file());   // => bool(false)

# get_include_path

get_include_path(): string|false

The directories `include` searches before the including file's own: `.`, the working directory. DIVERGENCE: the reference's value also names its PEAR directory.

var_dump(get_include_path());   // => string(1) "."

# get_included_files

get_included_files(): array

The main script's path (when it is a file) followed by every file `include`d or `require`d since, resolved, in load order and each once.

var_dump(get_included_files());   // => array(0) {
}

# get_required_files

get_required_files(): array

The alias of `get_included_files`.

# set_time_limit

set_time_limit(int $seconds): true

DIVERGENCE: accepted and ignored — no execution timer is installed. Always returns true.

var_dump(set_time_limit(30));   // => bool(true)

# ignore_user_abort

ignore_user_abort(?bool $enable = null): true

DIVERGENCE: accepted and ignored, storing no state, and returning true rather than PHP's previous-setting integer.

# error_reporting

error_reporting(?int $error_level = null): int

Read the error-reporting mask, or set it and return the PREVIOUS one. A diagnostic is displayed only when its `E_*` bit is set in the mask, so `error_reporting(0)` mutes every warning and notice. A missing argument and an explicit `null` both mean read-only. The mask starts at `E_ALL` unless `php -d error_reporting=…` seeded another. It cannot silence a COMPILE-time notice (`Using ${var} in strings …`), which was already decided when the file was read.

error_reporting(E_ALL & ~E_WARNING); echo $undefined; echo "quiet";   // => quiet

# error_get_last

error_get_last(): ?array

The last diagnostic raised, as `["type" => level, "message" => …, "file" => …, "line" => …]`, or null when none was raised since the start or since `error_clear_last()`. A diagnostic hidden by `@` or by `error_reporting` is still recorded, which is what makes `@f(); error_get_last()` the way to read a suppressed failure.

@file_get_contents("/nonexistent"); echo error_get_last()["type"];   // => 2

# error_clear_last

error_clear_last(): void

Forget the last diagnostic, so `error_get_last()` answers null until another is raised.

echo $u; error_clear_last(); var_dump(error_get_last());   // => NULL

# setlocale

setlocale(int $category, string|array|null $locales, string|array|null ...$rest): string|false

Hands each candidate locale in turn (an array's elements in order) to the C library's `setlocale` and returns the name of the first one accepted, or false. `"0"` queries without changing anything; `null` or `""` takes the locale from the environment. The `LC_*` category values are the platform's, and so is every answer, as in the reference — which also starts each run with `LC_CTYPE` at `C.UTF-8`. Nothing in phplang's own string or number formatting reads the locale.

var_dump(setlocale(LC_ALL, "C"), setlocale(LC_ALL, ["xx_XX", "POSIX"]));   // => string(1) "C" string(5) "POSIX"

# ini_get

ini_get(string $option): string|false

The current value of an ini setting, always as a STRING, or false when the engine has no such setting. `error_reporting` reads back what was last written to it — the decimal mask after `error_reporting()` or `-d`, but the RAW string after an `ini_set`, which is why `ini_set("error_reporting", "12abc")` leaves `ini_get` reporting `"12abc"` while the mask is 12. The settings known here are PHP core plus `date` and `pcre` — the two extensions PHP 8 cannot be built without — carrying the values the reference reports for them with NO php.ini loaded, which is how each was established. DIVERGENCE: a name belonging to an optional extension the reference happened to be built with (`mysqli.default_host`), or one whose default is that build's install prefix (`extension_dir`, `include_path`), reports false rather than a value that would be wrong on another machine.

var_dump(ini_get("memory_limit"), ini_get("nosuch"));   // => string(4) "128M" bool(false)

# ini_set

ini_set(string $option, mixed $value): string|false

Set an ini setting, returning its previous value as a string — or false, changing nothing, for a name the engine does not know (`ini_set` cannot invent settings) or one that is not runtime-changeable. That second group is PHP's `PHP_INI_PERDIR`/`PHP_INI_SYSTEM` set, which only a php.ini or `-d` may write while `ini_get` still reads it: `post_max_size`, `output_buffering`, `max_input_vars`, `expose_php`, `allow_url_fopen`, `arg_separator.input`, `disable_functions`, `hard_timeout`, `max_input_nesting_level`, `max_input_time`, `max_memory_limit`, `output_handler`, `register_argc_argv`, `zend.multibyte`, `zend.script_encoding`. Writing `error_reporting` also writes the mask, by ordinary string-to-int coercion and NOT the php.ini constant-expression scanner: `ini_set("error_reporting", "E_ALL & ~E_NOTICE")` reads as 0 and mutes everything, exactly as in the reference. The symbolic spelling works only on the `php -d error_reporting=…` path. DIVERGENCE: per-setting VALUE validation is not modelled — the reference refuses a value a setting will not take, with a warning and false, but `date.timezone` needs a zone database this build does not carry and `memory_limit`'s refusal quotes the process's live memory usage, which is not a reproducible number. Such a write is accepted here.

var_dump(ini_set("error_reporting", "0"), ini_get("error_reporting"));   // => string(5) "30719" string(1) "0"

# spl_object_id

spl_object_id(object $object): int

The raw heap handle. It is STABLE for the process lifetime — the object table is push-only, so an id is never recycled after the value dies. DIVERGENCE: it is not object-only — arrays, closures, generators, and resources all get an id, and a non-heap value returns 0 rather than raising a `TypeError`.

$a = new stdClass; $b = new stdClass; var_dump(spl_object_id($a) !== spl_object_id($b));   // => bool(true)

# spl_object_hash

spl_object_hash(object $object): string

The same handle rendered as 32 zero-padded lowercase hex digits. DIVERGENCE: real PHP mixes in a per-process seed; this is trivially reversible to the id, so it must not be treated as opaque.

echo strlen(spl_object_hash(new stdClass));   // => 32

# func_get_args

func_get_args(): array

The arguments AS PASSED to the enclosing call, read from a hidden frame variable. Variadic arguments ARE included; parameters filled from their defaults are not, matching PHP. DIVERGENCE: named arguments are appended in CALL order rather than placed at their parameter positions, and at global scope it returns an empty array rather than raising.

function f() { return count(func_get_args()); } echo f(1, 2, 3);   // => 3

# func_num_args

func_num_args(): int

How many arguments the enclosing call received. DIVERGENCE: outside a function it silently reports 0 instead of raising PHP's error.

function f() { return func_num_args(); } echo f(1, 2);   // => 2

# func_get_arg

func_get_arg(int $position): mixed

One argument of the enclosing call by position. DIVERGENCE: an out-of-range or negative position returns null instead of raising `ArgumentCountError` or `ValueError`.

function f() { return func_get_arg(1); } echo f("a", "b");   // => b

# iterator_to_array

iterator_to_array(mixed $iterator, bool $preserve_keys = true): array

Materializes an array or any `Traversable` — a generator, an `Iterator`, or an `IteratorAggregate` through the iterator it answers — walking it as `foreach` does. With `$preserve_keys` a repeated key keeps its last value; without it every element is kept. Anything else is the reference's `TypeError` (`must be of type Traversable|array`). Called from the program, it is a frame in a trace taken inside the iterator's methods.

echo count(iterator_to_array([1, 2, 3]));   // => 3

# iterator_count

iterator_count(mixed $iterator): int

Counts the elements a `foreach` over the argument visits, so a repeated key counts every time. Accepts what `iterator_to_array` accepts.

echo iterator_count([1, 2]);   // => 2

# iterator_apply

iterator_apply(mixed $iterator, callable $callback, ?array $args = null): int

DIVERGENCE: the subject is materialized ONLY to obtain a length, then the callback is invoked that many times with the elements of `$args` — it never receives the current element and the iterator is never advanced. Iteration stops early when the callback returns falsey. A generator yields a length of 0, so the callback never runs.

echo iterator_apply([1, 2, 3], fn() => true);   // => 3

Reflection

# class_exists

class_exists(string $class, bool $autoload = true): bool

A case-insensitive lookup in the host class table, answering for CLASSES only: an interface, a trait or an enum shares that table but is reported by its own predicate (an enum, as in PHP, is both). The engine's own classes `Closure` and `Generator` answer too. With `$autoload` (the default) a name not yet declared is handed to the autoloaders first.

interface I {} var_dump(class_exists("I"), class_exists("Closure"));   // => bool(false) bool(true)

# interface_exists

interface_exists(string $interface, bool $autoload = true): bool

True for a declared interface, and for the engine's own — `Traversable`, `Iterator`, `IteratorAggregate`, `Countable`, `ArrayAccess`, `Stringable`, `JsonSerializable`, `Throwable`, `UnitEnum`, `BackedEnum`. With `$autoload` (the default) a name not yet declared is handed to the autoloaders first.

interface I {} var_dump(interface_exists("I"), interface_exists("Traversable"));   // => bool(true) bool(true)

# trait_exists

trait_exists(string $trait, bool $autoload = true): bool

True for a declared trait and false for every other kind of name. With `$autoload` (the default) a name not yet declared is handed to the autoloaders first.

trait T {} var_dump(trait_exists("T"), class_exists("T"));   // => bool(true) bool(false)

# enum_exists

enum_exists(string $enum, bool $autoload = true): bool

True for a declared enum. An enum is the one name that is two kinds at once, so `class_exists()` answers for it as well — which is what PHP does.

enum E { case A; } var_dump(enum_exists("E"), class_exists("E"));   // => bool(true) bool(true)

# get_class

get_class(object $object = null): string

The object's class name in its original DECLARED casing. A non-object is a `TypeError` — returning `false` was PHP 7's answer — and a boolean is named in that message by its VALUE (`true given`), not as `bool`. Called with NO argument it answers the enclosing `__CLASS__` and raises `Deprecated: Calling get_class() without arguments is deprecated`; outside a class that form is an `Error` instead.

class Foo {} echo get_class(new Foo);   // => Foo

# get_called_class

get_called_class(): string

The late-static-binding class of the running frame — the same answer as `static::class`, including inside a closure, where it is the class the closure was created or bound under. Called with no class in scope it throws `Error: get_called_class() must be called from within a class`.

class A { static function f() { return get_called_class(); } } class B extends A {} echo B::f();   // => B

# get_parent_class

get_parent_class(object|string|null $object_or_class = null): string|false

The parent's name in declared casing, or `false` when there is none. It accepts an object, a class-name string, or nothing.

class A {} class B extends A {} echo get_parent_class(new B);   // => A

# get_object_vars

get_object_vars(object $object): array

The properties of the instance the CALLING SCOPE may see, in insertion order — public ones from outside the class, everything from inside a method of it. A non-object is a `TypeError`, including an array.

class C { public $a = 1; } print_r(get_object_vars(new C));   // => Array\n(\n    [a] => 1\n)

# get_class_methods

get_class_methods(object|string $object_or_class): array

The methods the class has, in the reference's function-table order — its own, then its traits', then each ancestor's it does not override (an enum adds `cases`/`from`/`tryFrom`) — keeping the private and protected ones only where the calling scope may call them. Anything but an object or a declared class name is the reference's `TypeError`. DIVERGENCE: names come back LOWERCASED.

class C { function Hello() {} } echo get_class_methods("C")[0];   // => hello

# get_class_vars

get_class_vars(string $class): array

The declared default of each property the calling scope can see: the class's own declarations first, then inherited ones, a typed property without a default as `null`, then statics at their declared default (not their current value). An enum reports `name` (and `value` when backed). An undeclared class raises `TypeError: get_class_vars(): Argument #1 ($class) must be a valid class name, <name> given`.

class C { public $a = 1; } print_r(get_class_vars("C"));   // => Array\n(\n    [a] => 1\n)

# get_declared_classes

get_declared_classes(): array

Every declared class and enum, in declared spelling and declaration order: the engine and prelude classes first, then the program's own. Interfaces and traits are listed by `get_declared_interfaces()` and `get_declared_traits()`. The internal classes are this build's, so their number and order differ from the reference's.

class C {} $c = get_declared_classes(); var_dump(end($c));   // => string(1) "C"

# get_declared_interfaces

get_declared_interfaces(): array

Every declared interface, in declared spelling and declaration order: the engine and prelude interfaces first, then the program's own.

interface I {} var_dump(in_array("I", get_declared_interfaces()));   // => bool(true)

# get_declared_traits

get_declared_traits(): array

Every declared trait, in declared spelling and declaration order. The prelude declares none the reference would list.

trait T {} print_r(get_declared_traits());   // => Array
(
    [0] => T
)

# class_parents

class_parents(object|string $object_or_class, bool $autoload = true): array|false

A nearest-first `name => name` map of the ancestor chain in declared casing, or `false` when the subject is neither an object nor a declared class.

class A {} class B extends A {} echo implode(",", class_parents(new B));   // => A

# class_implements

class_implements(object|string $object_or_class, bool $autoload = true): array|false

The interfaces the subject satisfies, transitively and through its parents, keyed by name. Engine ancestry answers too, so `class_implements("Generator")` reports `Iterator` and `Traversable`. An unknown name warns and returns `false`, as in PHP.

interface I {} class C implements I {} print_r(array_keys(class_implements(new C)));   // => Array\n(\n    [0] => I\n)

# class_uses

class_uses(object|string $object_or_class, bool $autoload = true): array|false

The traits THIS class composes with `use`, keyed by name — PHP does not walk the parent chain for it. An unknown name warns and returns `false`.

trait T {} class C { use T; } print_r(array_keys(class_uses("C")));   // => Array\n(\n    [0] => T\n)

# method_exists

method_exists(object|string $object_or_class, string $method): bool

Resolves the method through the class and its parents, comparing the name case-insensitively as PHP does. The engine classes answer too (`method_exists($gen, "current")`). A subject that is neither an object nor a string is the `TypeError` PHP declares on the parameter.

class C { function m() {} } var_dump(method_exists("C", "M"));   // => bool(true)

# property_exists

property_exists(object|string $object_or_class, string $property): bool

Checks the class's declarations, walking parents — instance and static properties and promoted constructor parameters, but not a private property an ancestor declared — and, for an OBJECT subject, a property present on the instance and reachable from the calling scope. The name is compared case-SENSITIVELY.

class C { public $a; } var_dump(property_exists("C", "a"));   // => bool(true)

# is_a

is_a(mixed $object_or_class, string $class, bool $allow_string = false): bool

True when the subject is, extends, or implements the named class, walking parents and interfaces transitively. `Throwable` is special-cased to match the `Exception` and `Error` roots even though no such class is declared. A string subject requires `$allow_string`.

class A {} class B extends A {} var_dump(is_a(new B, "A"));   // => bool(true)

# is_subclass_of

is_subclass_of(mixed $object_or_class, string $class, bool $allow_string = true): bool

The same ancestry walk as `is_a`, but the subject's own class is excluded first, so only strict ancestors and interfaces count.

class A {} class B extends A {}
var_dump(is_subclass_of(new B, "A"), is_subclass_of(new A, "A"));   // => bool(true) bool(false)

# __phplang_reflect

__phplang_reflect(string $op, mixed ...$args): mixed

Internal helper behind the prelude's `Reflection*` classes; a phplang extension with no PHP counterpart. Answers the engine's metadata — a class's flags, parent, interfaces and traits; its methods, properties and constants in the reference's order; a function's or method's parameters and their defaults — as arrays the prelude wraps in reflection objects.

Runtime and diagnostics

# __phplang_trace_string

__phplang_trace_string(array $trace): string

Internal helper behind the prelude's `Exception::getTraceAsString` and `Error::getTraceAsString`; a phplang extension with no PHP counterpart. Renders the structured frame array `getTrace()` returns as `#N file(line): Class->f(args)` lines closed by `#N {main}`; a frame without `file` reads `[internal function]`.

# __phplang_throwable_string

__phplang_throwable_string(Throwable $e): string

Internal helper behind the prelude's `Exception::__toString` and `Error::__toString`; a phplang extension with no PHP counterpart. Renders `Class: message in file:line` plus `Stack trace:` and the object's `getTraceAsString()` (`#0 {main}` when empty), omitting `: message` when the message is empty. The `previous` chain is walked and joined with `Next `, so the innermost exception reads first. A user function's argument `TypeError` / `ArgumentCountError` gains ` and defined`. A non-throwable argument yields an empty string.

# __phplang_obj_append

__phplang_obj_append(object $object, mixed $value): void

Internal helper behind the prelude's `ArrayObject` / `ArrayIterator` over an object; a phplang extension with no PHP counterpart. `$object[] = $value` through either stores `$value` under the next INTEGER key of the object's property table (`zend_hash_next_index_insert`), a key `$object->{"0"}` does not reach and `var_dump` prints as `[0]`.

# __phplang_obj_replace

__phplang_obj_replace(object $object, array $table): void

Internal helper behind the prelude's `ArrayObject` sorts over an object; a phplang extension with no PHP counterpart. The object's property table becomes `$table`, in its order, read the way `(array)` writes it: an integer key is an integer-keyed property and a mangled name (`"\0*\0p"`, `"\0Class\0p"`) the property it names.

# __phplang_spl_offset

__phplang_spl_offset(mixed $offset): int

Internal helper behind the prelude's `SplFixedArray` offsets; a phplang extension with no PHP counterpart. A port of `spl_offset_convert_to_ulong`: an int passes, a canonical integer string converts, a bool is 0/1, and a float takes the cast's `not representable` warning and the `loses precision` deprecation at the user's call site. Any other offset raises `TypeError: Cannot access offset of type <type> on SplFixedArray`.

# __phplang_warn

__phplang_warn(string $message): null

Internal helper for the prelude; a phplang extension with no PHP counterpart. Raises an `E_WARNING` with the message at the line of the innermost frame running user code, where the reference — whose method is internal — reports it (`CachingIterator::offsetGet()`'s `Undefined array key`).

# __phplang_list_ref_notice

__phplang_list_ref_notice(int $fetches): null

Internal helper behind a destructuring with a `&` target whose subject is a call result; a phplang extension with no PHP counterpart. Unless the call returned by reference, raises the reference's `Attempting to set reference to non referenceable value` notice once per by-reference fetch the pattern makes.

# __phplang_keys_after

__phplang_keys_after(array $array, array $walked): array

Internal helper behind a by-reference `foreach`; a phplang extension with no PHP counterpart. The keys of `$array` that follow the last key of `$walked` it still holds, in its order, or all of them when it holds none. The loop refills its key list from it when the list runs out, so an element the body appended is visited, as the reference's live hash iterator visits it.

# __phplang_deprecated

__phplang_deprecated(string $message): null

Internal helper for the prelude; a phplang extension with no PHP counterpart. Raises an `E_DEPRECATED` with the message at the line of the innermost frame running user code, where the reference — whose method is internal — reports it (`ArrayObject::__construct()`'s object-backing deprecation).

# __phplang_method_owner

__phplang_method_owner(object $object, string $method): ?string

Internal helper for the prelude; a phplang extension with no PHP counterpart. The lowercased name of the class declaring the method `$object` runs for `$method`, or null. `RecursiveIteratorIterator` uses it to tell a subclass's hook (`beginChildren()`, `callHasChildren()`, …) from the inherited no-op, which `spl_recursive_it_it_construct` likewise leaves uncalled.

# __phplang_try_call

__phplang_try_call(Closure $fn): array

Internal helper for the prelude, which cannot hold a `try` block: runs the closure and answers `[true, $result]`, or `[false, $exception]` with the exception it threw taken off the stack. A phplang extension with no PHP counterpart.

# assert

assert(mixed $assertion, mixed $description = null): bool

Evaluates the assertion for truthiness and RETURNS it. DIVERGENCE: this inverts PHP 8's contract — PHP always returns true and throws `AssertionError` on failure, whereas here `assert(false)` simply returns false and throws nothing. `$description` is never read.

var_dump(assert(1 === 1), assert(false));   // => bool(true) bool(false)

# assert_options

assert_options(int $option, mixed $value = null): int

DIVERGENCE: a stub that always returns 0 and stores nothing. No argument is read.

echo assert_options(1);   // => 0

# trigger_error

trigger_error(string $message, int $error_level = E_USER_NOTICE): bool

Prints `"<label>: <message>"` to STDERR and returns true. The label is `Fatal error` for `E_USER_ERROR`, `Warning` for `E_USER_WARNING`, `Deprecated` for `E_USER_DEPRECATED`, and `Notice` for everything else. DIVERGENCE: `E_USER_ERROR` does NOT halt — execution continues with the next statement.

trigger_error("careful", E_USER_WARNING); echo "still running";   // => still running

# user_error

user_error(string $message, int $error_level = E_USER_NOTICE): bool

The alias of `trigger_error`, sharing its match arm and its non-halting `E_USER_ERROR` behaviour.

# error_log

error_log(string $message, int $message_type = 0, string $destination = ""): bool

With `$message_type` 3 AND a destination it really appends the raw message bytes to that file — no timestamp and no trailing newline are added. Every other combination writes the message to stderr and returns true. The email and SAPI-logger message types are not implemented.

error_log("note", 3, "/tmp/php_ref_log.txt"); echo file_get_contents("/tmp/php_ref_log.txt");   // => note

# debug_backtrace

debug_backtrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT, int $limit = 0): array

The call stack as a list of frames, innermost first, each an array with `file` and `line` of the call (absent when internal code made it), `function`, and for a method `class`, `object` (unless `$options` lacks `DEBUG_BACKTRACE_PROVIDE_OBJECT`) and `type` (`->` or `::`), then `args` (unless `DEBUG_BACKTRACE_IGNORE_ARGS`). An `include`/`require`/`eval` frame is one more entry, with `args` before `function`. `$limit` caps the list. The global scope is not a frame, so top-level code gets an empty array.

function f() { return count(debug_backtrace()); } echo f();   // => 1

# debug_print_backtrace

debug_print_backtrace(int $options = 0, int $limit = 0): null

Prints the frames of `debug_backtrace()` the way `getTraceAsString()` does — `#0 file(line): f(args)` — without the closing `{main}` line. `DEBUG_BACKTRACE_IGNORE_ARGS` drops the argument lists and `$limit` caps the frame count.

function f() { debug_print_backtrace(); } f();   // => #0 Command line code(1): f()

# set_error_handler

set_error_handler(?callable $callback, int $error_levels = E_ALL): null

Pushes the handler (null pushes "none") with the levels it takes and returns the handler it replaces. A warning, notice or deprecation of a level it takes is handed to it as `($errno, $errstr, $errfile, $errline)` instead of being displayed — even under `@`, where `error_reporting()` reads 4437 inside it; returning `false` displays it after all. A diagnostic the handler raises itself takes the default path. `trigger_error(…, E_USER_ERROR)` reaches it too, and is fatal only when it returns `false`. DIVERGENCE: the handler runs at the next builtin boundary after the diagnostic, so one raised in the middle of a library call that goes on to print runs after that output.

set_error_handler(function ($n, $s) { echo "caught: $s\n"; return true; });
echo $undefined;   // => caught: Undefined variable $undefined

# set_exception_handler

set_exception_handler(?callable $callback): null

Pushes the handler (null pushes "none") and returns the one it replaces. An exception that reaches the top of a FILE or STDIN script is handed to it instead of the fatal, and the run then ends normally (status 0); one the handler throws is the uncaught one. Under `php -r` it is never called, as in the reference, whose `zend_eval_string` reports the exception itself.

# restore_error_handler

restore_error_handler(): bool

Pops the handler stack back to the previous `set_error_handler`; always returns true.

var_dump(restore_error_handler());   // => bool(true)

# restore_exception_handler

restore_exception_handler(): bool

Pops the handler stack back to the previous `set_exception_handler`; always returns true.

# register_shutdown_function

register_shutdown_function(callable $callback, mixed ...$args): null

Queues the callback with its arguments. At request end the queue runs in order (one registered during the run is run too), after an `exit` and after any displayed fatal error, before the destructors; an exception one lets escape is reported uncaught and ends the sweep.

register_shutdown_function(fn($w) => print("bye $w\n"), "now");   // prints at exit: bye now

# spl_autoload_register

spl_autoload_register(?callable $callback = null, bool $throw = true, bool $prepend = false): bool

Adds `$callback` to the autoload chain (at the front with `$prepend`); a callable already in it is not added again. When a class, interface, trait or enum that does not exist is needed — `new`, a static call, constant or property, `extends`/`implements`, `class_exists()` and the other lookups that autoload — each loader is called with the name (no leading `\`) until it exists. A loader that throws ends the chain with its exception. `$throw = false` is ignored with a notice. A null `$callback` registers the default `spl_autoload`.

spl_autoload_register(fn($c) => eval("class $c {}")); echo get_class(new Lazy);   // => Lazy

# spl_autoload_unregister

spl_autoload_unregister(callable $callback): bool

Removes `$callback` from the autoload chain; false when it was not in it.

# spl_autoload_functions

spl_autoload_functions(): array

The registered autoloaders, in the order they are called.

spl_autoload_register('strlen'); var_dump(spl_autoload_functions() === ['strlen']);   // => bool(true)

# spl_autoload

spl_autoload(string $class, ?string $file_extensions = null): void

The default autoloader: the class name lowercased with `\` turned into `/`, each of `$file_extensions` (else `spl_autoload_extensions()`) appended in turn and looked up along the include path, and the first file found included once.

# spl_autoload_extensions

spl_autoload_extensions(?string $file_extensions = null): string

The comma-separated extensions `spl_autoload` tries — `.inc,.php` until a call sets them.

echo spl_autoload_extensions();   // => .inc,.php

# spl_autoload_call

spl_autoload_call(string $class): void

Runs the autoload chain for `$class`, stopping at the first loader after which it exists.

# get_defined_vars

get_defined_vars(): array

The current frame's bound variables, in the order they were first bound. An unset name is absent; a name bound to `null` is present. `$this` and `$GLOBALS` are not included. At global scope the populated superglobals come first in the reference's fixed order (`argv`, `argc`, `_GET`, `_POST`, `_COOKIE`, `_FILES`, `_SERVER`), then the script's own variables.

function f($p) { $a = 1; unset($a); return get_defined_vars(); } print_r(f(7));   // => [p => 7]

# class_alias

class_alias(string $class, string $alias, bool $autoload = true): bool

DIVERGENCE: it reports whether `$class` exists and REGISTERS NOTHING — `$alias` is never read. A true return is therefore misleading: instantiating the alias afterwards still fails.

class C {} var_dump(class_alias("C", "D"), class_exists("D"));   // => bool(true) bool(false)

Callables

# call_user_func

call_user_func(callable $callback, mixed ...$args): mixed

Invokes any of the five accepted callable forms with the remaining arguments: a `Closure`, a `"function"` name, a `"Class::method"` string, `[$obj, "method"]`, or `["Class", "method"]`. Method names resolve case-insensitively.

echo call_user_func("strtoupper", "hi");   // => HI

# call_user_func_array

call_user_func_array(callable $callback, array $args): mixed

An INTEGER key contributes a positional argument, in order; a STRING key contributes a NAMED one, bound to the parameter it spells — the same reading `f(...$array)` gives. A non-array second argument raises the reference's `Argument #2 ($args) must be of type array` TypeError. The `Closure` that first-class callable syntax `f(...)` builds forwards its arguments through this function, which is what carries `$f(b: 2)` to the parameter it names.

echo call_user_func_array("max", [1, 5, 3]);   // => 5

# function_exists

function_exists(string $function): bool

Exact for USER functions, which are looked up in the real function table. Builtin coverage is derived from the corpus — the registry a stdlib function is already required to be listed in — so it answers for every name this build dispatches, minus the handful the corpus itself documents as absent from reference PHP (`__cast_array`, `__cast_object`, `gmp_pow2`), which a PHP program must not see.

function myFn() {} var_dump(function_exists("myFn"), function_exists("strlen"));   // => bool(true) bool(true)

Constants

# define

define(string $constant_name, mixed $value, bool $case_insensitive = false): bool

Inserts a constant, returning false when the name already exists — including any of the 156 predefined ones. DIVERGENCE: a failed redefinition prints no warning, the third argument is never read, and an omitted value stores null.

define("PHP_REF_C", 5); echo PHP_REF_C;   // => 5

# defined

defined(string $constant_name): bool

Whether a constant of that exact name exists. Lookup is case-SENSITIVE, unlike class and function lookup, so `define("FOO", 1)` leaves `defined("foo")` false.

define("PHP_REF_D", 1); var_dump(defined("PHP_REF_D"), defined("php_ref_d"));   // => bool(true) bool(false)

# constant

constant(string $name): mixed

The value of the named constant. An UNDEFINED name throws `Error: Undefined constant "<name>"`, catchable, exactly as a bare reference to the same name does.

echo constant("NOPE");   // => NOPE

Input filtering

# filter_var

filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed

Applies one filter. `$options` may be a bare flags bitmask or a `['flags' => …, 'options' => …]` map. A failing VALIDATOR returns false, or null when `FILTER_NULL_ON_FAILURE` is set; sanitizers cannot fail. DIVERGENCE: an ARRAY value fails every filter; `FILTER_CALLBACK`, `FILTER_SANITIZE_ENCODED`, and `FILTER_SANITIZE_ADD_SLASHES` are unimplemented and silently return the raw string; and `options['default']` is never consulted.

var_dump(filter_var("42", FILTER_VALIDATE_INT), filter_var("x", FILTER_VALIDATE_INT));   // => int(42) bool(false)

# filter_var_array

filter_var_array(array $array, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false

Filters many fields at once. With a definition array the output is keyed by the DEFINITION — data keys it does not mention are dropped, and fields missing from the data become null. With a bare id, that filter applies to every field. A non-array subject returns false. DIVERGENCE: `$add_empty` is never read, so missing fields are always emitted.

print_r(filter_var_array(["a" => "1"], ["a" => FILTER_VALIDATE_INT]));   // => Array\n(\n    [a] => 1\n)

# filter_has_var

filter_has_var(int $input_type, string $var_name): bool

DIVERGENCE: hardcoded `false`, reading neither argument. phplang is a standalone runtime with no request context, so there is no `$_GET` or `$_POST` to consult.

var_dump(filter_has_var(INPUT_GET, "q"));   // => bool(false)

More