Browse entries
Based on the PHP manual, comparing how C / C++ / C# / Go / Java / JavaScript / PHP / Python / Rust / TypeScript write each topic, with real execution output.
Entries
524 entries
constant
Returns the value of a constant given its name (a runtime reflection lookup for constants).
define
Defines a named constant at runtime (complementing the const keyword).
empty
Checks whether a variable is empty (a language construct: "", 0, "0", null, false, [] and undefined all count as empty).
get_defined_vars
Returns every defined variable in the current scope (in a function: parameters plus in-body variables; globally, superglobals too) - a dynamic-language introspection feature.
getenv
Reads process environment variables: by name (false when absent; omit the name for the whole environment array); values written by putenv are immediately visible to later reads in the same process.
gettype
Returns the variable's type name string (historical names: float as double, int as integer); prefer get_debug_type for debugging.
isset
Determines whether a variable is declared and is not null (a language construct that accepts multiple variables).
putenv
Mutates this process's environment block with "NAME=value" syntax (add or overwrite); a bare "NAME" without "=" deletes. The change affects only this process and children spawned afterwards, and is restored at the end of the request (web context).
unset
Destroys the given variable or array key (a language construct that accepts multiple targets).
addcslashes
Escapes a string C-style for the given character list (\n\t\0 become C escape sequences; ranges use the ".." syntax) — pairing with addslashes's "quote-like characters only" strategy.
addslashes / stripslashes
Escapes single quotes, double quotes, backslashes and NUL with backslashes, plus its inverse. A magic-quotes-era legacy: the manual explicitly warns it does NOT prevent SQL injection - prepared statements are the correct approach.
base64_decode
Decodes a base64-encoded string back to the original bytes.
base64_encode
Encodes data with MIME base64 (output without line breaks).
bin2hex / hex2bin
Binary string to hex string and back (byte level: every byte becomes two hex characters) — the counterpart of numeric-level dechex/hexdec (byte sequences vs formatting an integer); Python bytes.hex, Node Buffer hex and Go encoding/hex are the direct equivalents.
chr / ord
Byte-to-number conversions: chr builds a single-byte string from an unsigned byte (0-255) and ord reads the first byte — multi-byte UTF-8 characters must be built byte by byte; chr/ord in Python/Rust are codepoint-based, a fundamental difference from PHP's byte semantics.
chunk_split
Splits a string into fixed-length chunks with a separator inserted after each (default \r\n) — built for folding base64 into lines for MIME (RFC 2045); most languages have no direct counterpart and hand-write the loop.
convert_uuencode / convert_uudecode
Legacy uu encoding/decoding (length-prefixed lines, 3 bytes to 4 chars +32) — a 6bit scheme like base64 but with line structure and a ~ terminator; same encoding efficiency as base64 with more container overhead. Python's binascii matches byte for byte; other languages hand-roll it.
count_chars
Byte-level string statistics: mode 0 full table / 1 present only / 2 absent only / 3 present as string / 4 absent as string - a 256-slot byte histogram.
explode
Splits a string into an array by a delimiter.
get_html_translation_table
Returns the translation table used internally by htmlspecialchars/htmlentities (character → entity); HTML_SPECIALCHARS holds the five markup characters, HTML_ENTITIES the full set (~1500 entries under HTML5); the default flags include ENT_QUOTES since 8.1.
grapheme_strlen
Counts grapheme clusters (user-perceived characters): strlen counts bytes, mb_strlen counts code points, grapheme_strlen counts graphemes — precomposed é and decomposed é both count as 1, and the ZWJ family emoji counts as a single grapheme.
grapheme_strrev
Reverses a string by grapheme cluster (new in PHP 8.6, Intl): emoji ZWJ sequences and combining marks stay intact.
grapheme_substr
Substring by grapheme cluster: taking grapheme [1,2) of "a👨👩👧b" yields the whole family emoji, not half a code point — mb_substr with the same arguments returns only the MAN; negative offsets count from the tail, and out-of-range yields an empty string.
html_entity_decode
Converts HTML entities back to characters — the inverse of htmlentities.
htmlentities
Converts every character with an HTML entity equivalent to that entity (broader coverage than htmlspecialchars).
htmlspecialchars
Converts HTML-sensitive characters (& < > quotes) to entities — the first line of defense against XSS.
implode
Joins array elements into a single string with a delimiter.
lcfirst
Makes a string's first character lowercase.
levenshtein
Computes the Levenshtein edit distance between two strings: the minimum number of single-character insertions, deletions or substitutions.
ltrim / rtrim
Directed trimming: ltrim cuts only the left side and rtrim only the right (same default whitespace set as trim); charlist is a character SET, not a prefix/suffix string — ltrim('Hello, World!', 'He') strips the characters H and e, not the string 'He'.
mb_convert_encoding
Character encoding conversion (UTF-8/GBK/ISO-8859-1): a fixed string makes the UTF-8 -> GBK -> UTF-8 round trip lossless; compared with encode/decode, iconv, TextDecoder and Encoding across languages.
mb_detect_encoding / mb_check_encoding
Encoding detection and validation: mb_detect_encoding guesses the likeliest encoding from a candidate list (mb_detect_order: ASCII, UTF-8), while mb_check_encoding strictly validates one encoding (defaulting to the internal one); detection is probabilistic, validation gives the definite answer.
mb_internal_encoding
Sets/gets the process-wide default multibyte encoding - the implicit value behind every mb_* call that omits its encoding argument. Global mutable state: modern style prefers passing it explicitly.
mb_scrub
Replaces ill-formed byte sequences with the substitute character (default ?, settable to U+FFFD via mb_substitute_character) - the data-cleaning gate: scrub dirty input before processing.
mb_str_split / mb_strtoupper / mb_strtolower
Two-track splitting and casing: byte-cutting str_split (tears multibyte chars) vs character-cutting mb_str_split; mb_strtoupper/mb_strtolower map by Unicode properties and are locale-independent — "i" is always "I", while Turkish İ/ı needs hand mapping.
mb_strlen
Gets the character count of a string (multibyte-safe), contrasted with the byte count.
mb_strpos / mb_stripos / mb_strrpos / mb_strripos
Multibyte-safe search returning CHARACTER positions - the core contrast with strpos's byte positions: for '世界' in '你好,世界', mb gives 3 while bytes give 9.
mb_strwidth
Measures string width in terminal columns: halfwidth = 1, East Asian fullwidth = 2 (UAX #11) - the root cause of str_pad failing to align CJK text, and the fix.
mb_substr
Multibyte-safe character-level substring: contrasted with byte-level substr to demonstrate PHP's dual-track string API — most languages have naturally character-level strings with no mb_ prefix.
mb_ucfirst / mb_lcfirst
Multibyte-safe first-letter case conversion (PHP 8.4+) - mbstring's answer to ucfirst/lcfirst being ASCII-only: multibyte letters like z with caron finally convert.
nl2br
Inserts an HTML line-break tag (default <br />, XHTML style) before every newline in a string; no HTML escaping.
number_format
Formats a number with grouped thousands and a fixed number of decimal places.
printf / vprintf / vfprintf / fprintf / vsprintf
The formatted-output family: printf/fprintf write straight to a stream and return the byte count (contrast sprintf, which returns the string); the v* prefix takes an ARRAY of arguments (va_list/array instead of a variadic list).
quoted_printable_encode / quoted_printable_decode
MIME quoted-printable (RFC 2045 §6.7): non-ASCII bytes become =XX, '=' becomes =3D, lines soft-break at 75 chars (trailing '='); encode emits CRLF per the RFC; decode only expands =XX sequences.
quotemeta
Escapes the string-domain metacharacters: backslash-prefixes each of the POSIX set . \ + * ? [ ^ ] ( $ - unlike preg_quote, which escapes the regex domain; an empty string returns "" (not false) since 8.0.
similar_text
Computes string similarity: returns the number of matching characters, with an optional by-reference percentage (2×matching/(len1+len2)×100); paired with levenshtein as similarity vs edit distance.
soundex
The Soundex phonetic code: names map to a letter-plus-three-digits code so similar-sounding names collide - old but effective fuzzy name retrieval.
sprintf
Builds a formatted string from a format string and arguments.
sscanf
The input counterpart of printf(): parses fields out of a string by a format; the two-argument form returns the parsed array, while the by-reference form returns the number of fields assigned.
str_contains
Determines if a string contains a given substring and returns a boolean.
str_ends_with
Checks if a string ends with a given suffix.
str_increment / str_decrement
PHP 8.3 alphanumeric increment/decrement: rightmost digit +1 with carry (z wraps to a, 9 wraps to 0); an all-carry prepends a same-family character (zz→aaa, ZZ→AAA, 99→100); no builtin elsewhere - hand-write it.
str_ireplace
Case-insensitive replace: the case-insensitive twin of str_replace (ASCII-only folding since 8.2); array arguments map pairwise in order; &$count receives the replacement count.
str_pad
Pads a string to a given length with another string.
str_repeat
Repeats a string a given number of times.
str_replace
Replaces occurrences of a substring with another substring.
str_rot13 / str_shuffle
Classic miscellany: ROT13, the self-inverse Caesar shift (applying it twice restores the input), and string shuffling (per the PHP manual NOT cryptographically secure - global Mt19937, no injectable engine).
str_split
Splits a string into an array: single bytes by default, or fixed-length chunks; on multi-byte strings it splits BYTES, not characters (mb_str_split is the character-level counterpart).
str_starts_with
Checks if a string starts with a given prefix.
str_word_count
Counts words in a string: a word is an alphanumeric run that may contain (but not start with) ' and -; format 0 returns the count, 1 the word array, 2 an offset-to-word map — the word-level counterpart of count_chars' byte-level histogram; single-byte implementation, multibyte text needs the regex route.
strcasecmp / strncasecmp
Binary-safe case-insensitive comparison: same sign semantics as strcmp/strncmp, ASCII-only folding (locale-independent since 8.2); only the sign of the result is portable.
strcmp / strncmp
Binary-safe string comparison: returns the sign of the difference (<0/0/>0), not a bool - only the sign is portable (PHP 8.2+ no longer guarantees the strlen difference); strncmp compares only the first n characters.
strip_tags
Strips HTML and PHP tags from a string (with an optional whitelist of tags to keep).
stripos / stristr
Case-insensitive search: stripos returns the first-match position (int|false, test with ===), stristr returns the tail from the match (before_needle flips to the head); ASCII-only folding.
strlen
Returns the byte length of a string.
strpbrk
Scan for the first occurrence of ANY character from a charset: returns the tail from that position (not an index); false when nothing matches; an empty charset throws ValueError (8.0+).
strpos
Finds the position (index) of the first occurrence of a substring.
strrchr
Take from the LAST occurrence to the end (the reverse-direction mirror of strstr); before_needle (8.3+) flips to the head; false when not found.
strrev
Reverses a string.
strrpos / strripos
Finds the position of the LAST occurrence of a substring (the reverse-search member of the strpos family); strripos is its case-insensitive variant. Returns false (not -1) on miss, and a match at position 0 needs !== false.
strspn / strcspn
Character-set spans: strspn returns the length of the initial segment consisting entirely of characters in the set, strcspn the initial segment containing none of them. The purest C-lineage string functions, commonly used for input validation (strspn result equal to strlen means the whole string is legal).
strstr
Finds the first occurrence of a substring and returns the substring itself: from the match to the end by default, or the part before the match with before_needle=true; returns false on a miss.
strtok
Tokenizes a string by a delimiter set: only the first call takes the string, later calls take the delimiter only (the cursor lives in internal state); contiguous delimiters merge and leading/trailing ones are ignored — the opposite of explode, which keeps empty segments.
strtoupper
Converts all letters in a string to uppercase.
strtr
String translation: the two-string form maps characters one-to-one, the array form matches longest key first in a single pass without rescanning replaced text — the classic contrast with str_replace's order-sensitive cascading.
substr
Extracts a portion of a string.
substr_compare
Compares a window of haystack starting at the given offset against needle: equivalent to strcmp(substr(haystack, offset, length), needle) — a -1/0/+1 tri-state; length caps the window, case_insensitive ignores case; the single-function composition of the existing strcmp/substr entries.
substr_count
Counts how many times a substring occurs in a string (non-overlapping), with an optional offset/length window.
substr_replace
Replaces the portion of a string delimited by offset/length with a replacement string; omitting length replaces to the end, length 0 becomes pure insertion, a negative offset counts from the end - complementary to str_replace's global replacement.
trim
Strips whitespace from both ends of a string.
ucfirst
Converts the first letter of a string to uppercase.
ucwords
Uppercases the first character of each word. The default word boundaries are only the six whitespace characters (space/tab/CR/LF/FF/VT) - apostrophes and hyphens do not count. Python's title() and C#'s ToTitleCase follow different rules; see the comparison.
urldecode
Decodes a URL-encoded string: %XX hexadecimal escapes become characters and plus signs become spaces.
urlencode
Encodes a string per application/x-www-form-urlencoded (spaces become plus signs, other unsafe characters become %XX).
wordwrap
Wraps a string at spaces to a given width, optionally cutting words longer than that width.
Collator::sort
ICU-powered locale sorting: a Collator carrying its own locale rules sorts an array in place (the locale-aware equivalent of sort()), and is the official replacement for strcoll/SORT_LOCALE_STRING deprecated as of PHP 8.6. Under en_US, apple sorts before Ápple — collation keys are maintained release-by-release by ICU and stable across platforms.
gettext
GNU gettext message translation: looks the msgid up in the current domain's .mo catalog, returning the translation when found and the msgid unchanged when not — this entry deliberately ships no catalog and demos the zero-dependency, genuinely runnable flow via the fallback behaviour (bindtextdomain + textdomain + the _() alias).
idn_to_ascii
Converts an internationalized domain name to IDNA ASCII (punycode): non-ASCII labels become xn-- labels, pure-ASCII ones are only lowercased; UTS #46 is the default variant. The Chinese domain 例子.cn becomes xn--fsqu00a.cn — the UTS #46 rules are frozen, so output is identical across ICU versions.
IntlDateFormatter
ICU's date-formatting binding for PHP: locale plus a canned style (SHORT/LONG/FULL) or an explicit pattern decides the output shape, and it can parse back to a timestamp. Sibling of JS Intl.DateTimeFormat and Java DateTimeFormatter.ofLocalizedDate. The example pins a UTC timestamp and uses explicit patterns to sidestep ICU version drift.
NumberFormatter
ICU's binding for number/currency/percent formatting: renders locale-specific number strings by locale and style (DECIMAL/CURRENCY/PERCENT/SPELLL and friends), with a reversible parse(). The example pins en_US asserting "1,234.56" — pure numeric patterns are stable across ICU versions; currency symbols drift far more, so they are discussed in the notes only, never in code.
setlocale
Sets the process-wide locale (the global school): categories such as LC_ALL/LC_NUMERIC/LC_TIME/LC_COLLATE govern subsequent libc behaviour; returns the locale that actually took effect, or false on failure. After a successful de_DE switch printf's decimal point becomes a comma — always restore afterwards.
Transliterator
The ICU transliteration engine: one ID chain generates slugs ("Any-Latin; Latin-ASCII; Lower(); [^a-z0-9] Remove") — "Crème Brûlée" folds to ASCII deterministically; Han-to-pinyin (Any-Latin) varies with the ICU version.
array_change_key_case
Converts all array keys to lowercase or uppercase (CASE_LOWER/CASE_UPPER); the dedicated tool for normalizing HTTP headers and config keys.
array_chunk
Splits an array into chunks of a fixed length.
array_column
Extracts the values of a given column from a two-dimensional array.
array_combine
Creates a map array using one array as keys and the other as values; both arrays must have equal length.
array_count_values
Counts occurrences of each value in an array, returning a map of value => count (a value histogram). Elements must be int/string; the result keeps first-seen order.
array_diff
Computes the array difference: values in the first array that are absent from the others, preserving order and keys.
array_diff / array_intersect family
Two set-operation families: difference (diff) and intersection (intersect), each with key / assoc / uassoc / ukey comparison variants. Values compare loosely as strings, keys and order are kept — the complete PHP array set-operation toolbox.
array_fill
Fills an array with a given value a specified number of times, starting at a chosen index.
array_fill_keys
Fill from a key array: the values of $keys become the keys and one shared $value fills the whole table (the mirror direction of array_fill, which fills by index range); numeric-string keys coerce to int per PHP convention.
array_filter
Filters array elements with a callback function.
array_flip
Swaps keys with values in an array (on duplicate values the later key wins).
array_intersect
Computes the array intersection: values present in every array, ordered by the first array.
array_is_list
Whether the array is a "true list" (sequential 0..n-1 integer keys); the health-check tool for PHP's two array faces - json_encode emits an array or an object depending on which face shows.
array_key_exists
Checks whether a key exists regardless of its value — the correct answer to the classic trap where isset() returns false for keys whose value is null.
array_key_first
Gets the first key of an array without moving the internal pointer.
array_key_last
Gets the last key of an array without moving the internal pointer.
array_keys
Returns all keys of an array.
array_map
Applies a callback to every element of an array and returns a new array.
array_merge
Merges one or more arrays.
array_merge_recursive / array_replace_recursive
Recursive merging and replacing of nested arrays: merge_recursive aggregates colliding scalar values into an array (port becomes [3306,5432]), while replace_recursive lets the later array overwrite deep down. Neither mutates the originals — the behavioral contrast is the key point when merging configs.
array_all / array_any / array_find …
PHP 8.4's modern callback quartet (array_all/array_any/array_find/array_find_key - callback takes value and key, short-circuits) plus 8.5's array_first/array_last, each with its native counterpart in other languages.
array_pad
Pads an array to a given length: positive pads right, negative pads left, and the array is returned untouched when long enough; pairs with array_slice as the truncate+pad pagination combo.
array_pop
Pops and returns the last element of the array, shortening the array by one element.
array_push
Pushes one or more elements onto the end of the array and returns the new count (equivalent to $array[] = $value).
array_rand
Picks one or more random keys from an array (a single pick returns the key itself; multiple picks return keys in original order). Since 7.1 it shares the global Mersenne Twister with mt_rand, so mt_srand makes it reproducible; not cryptographically secure.
array_reduce
Reduces an array to a single value using a callback.
array_replace
Later arrays overwrite earlier ones key by key, returning a new array: assignment-replacement, not recursive merging — nested arrays are swapped wholesale (timeout disappears), the shallow counterpart of the existing array_replace_recursive's deep merge.
array_reverse
Returns a new array with the elements in reversed order.
array_search
Searches an array for a value and returns its key, or false when not found.
array_shift
Removes and returns the first element of the array, shifting the remaining elements one position forward.
array_slice
Extracts a slice of an array.
array_splice
Removes and replaces a segment in place: modifies the original array and returns the removed part; complements read-only array_slice. Negative offsets count from the tail; replacement keys are not preserved.
array_sum / array_product
Numeric aggregation: array_sum adds and array_product multiplies; empty arrays return the additive/multiplicative identities 0 and 1; float accumulation follows array order.
array_unique
Removes duplicate values from an array.
array_unshift
Prepends one or more elements to the beginning of the array and returns the new element count.
array_values
Returns all values of an array (rebuilding numeric indexes).
array_walk
Applies a callback to every element in place (the callback may modify elements by reference).
array_walk_recursive
Recursively walks nested arrays and calls back only on scalar leaves — contrast with array_walk (single level): the depth difference decides the use case; no direct counterpart in other languages, hand-write recursion or tree enumeration.
compact / extract
A two-way bridge between variables and arrays: compact packs variables into an array by name; extract imports array keys into the current symbol table as variables. extract overwrites same-named variables by default — never use it on untrusted data.
count
Counts the number of elements in an array.
in_array
Checks whether a value exists in an array.
range
Range arrays: eagerly builds an arithmetic array from start/end/step — integers auto-detect direction (no negative step needed), characters have builtin sequences (range('a','e')), float steps are allowed; the end is included in the result (opposite of Python's exclusive stop).
sort
Sorts array elements in place in ascending order.
array_multisort
Sorts multiple arrays jointly in the given order, keeping elements aligned across arrays.
arsort
Sorts an array in place descending by value while keeping key-value association.
asort
Sorts an array in place ascending by value while keeping key-value association.
ksort
Sorts an array in place ascending by key while keeping key-value association.
natsort
Natural order: digit segments compare by value (img2 < img10), text segments lexically; key-value bindings kept; natcasesort is the case-insensitive variant.
rsort
Sorts array elements in place in descending order.
shuffle
Shuffles array elements randomly (values kept, keys rebuilt as integers; associative keys lost); not cryptographically secure, seedability only via the global mt_srand.
usort
Sorts an array in place with a user-supplied comparison callback and rebuilds numeric indexes.
ArrayIterator
An iterator VIEW over an array: the Iterator protocol (rewind/valid/current/key/next) plus seek and array access, mutable while iterating; a different job from ArrayObject's container wrapping.
ArrayObject
Wraps an array into an object container (array access, counting, iteration, serialization), subclassable for extra behavior.
iterator_count / iterator_apply
Iterator helpers: iterator_count counts elements but consumes a forward iterator (the position does not survive); iterator_apply calls a callback per element (it must return true to continue) and returns the iteration count.
LimitIterator / CallbackFilterIterator / RegexIterator
The SPL decorator trio layered on iterators: limit (LimitIterator), callback-filter (CallbackFilterIterator), regex-filter (RegexIterator) - a lazy pipeline, complementing the concrete structures SplStack/SplQueue.
iterator_to_array
Materializes a lazy iterator/generator into an array; with preserve_keys=true later duplicates overwrite (manual-stated), false keeps all values with rebuilt keys.
RecursiveIteratorIterator
The outer wrapper that flattens a RecursiveIterator (directory tree, nested arrays) into one linear stream: LEAVES_ONLY by default, getDepth() reports level - recursive traversal is a scenario, not a function.
spl_autoload_register
Registers a function into the SPL autoload queue; it fires on demand the first time an undefined class is used.
spl_object_id
Unique integer handle for an object: same object always yields the same id, distinct objects differ (the numeric id is not pre-determined, so the example asserts booleans); identity-vs-equality compared across languages; replaces spl_object_hash (deprecated since 8.6).
SplDoublyLinkedList
The generic SPL doubly-linked list: O(1) push/unshift at both ends, pop/shift from both ends, FIFO/LIFO iteration modes; SplStack/SplQueue are thin subclasses of it.
splfileobject
The SPL object-oriented way to read files: foreach iterates lines directly (key is the line number, current the line), seek jumps to a line, setFlags(DROP_NEW_LINE) strips trailing newlines — a dual-track counterpart to procedural fopen/fgets, another stop on PHP's "procedural vs OOP" theme.
splfixedarray
A fixed-length array: its size is set at construction (changed manually via setSize), it accepts only integer keys, uninitialized slots are NULL, and it is memory-compact — a fundamental contrast to the regular PHP array (auto-growing, mixed keys, hash-bucket overhead); out-of-bounds access throws OutOfBoundsException.
SplMinHeap / SplMaxHeap
Ready-made subclasses of the abstract binary heap: SplMinHeap/SplMaxHeap order themselves via compare(), insert/extract O(log n); iterating a heap drains it.
splobjectstorage
A storage keyed by object identity: one slot per object; attach/contains/detach (deprecated since 8.5 — prefer the offset* API) can also carry associated data, serving as both an object set and an object-to-data map: the container form of identity-vs-equality (see spl_object_id).
splpriorityqueue
A max-heap priority queue: insert(value, priority) enqueues, extract dequeues, top peeks, isEmpty checks — extraction always yields the highest priority, but the order of equal-priority items is undefined (the demo uses distinct priorities for determinism); the extraction mode is tunable via setExtractFlags.
SplQueue
SPL's doubly-linked-list queue (FIFO) with O(1) enqueue and dequeue on both ends.
SplStack
SPL's doubly-linked-list stack (LIFO) with O(1) push and pop on both ends.
crc32
The CRC-32 checksum (IEEE 802.3 polynomial 0xEDB88320) — checksums detect transmission corruption, not tampering, a different tool from the md5/sha cryptographic hash family; languages without a built-in implement the classic table-driven algorithm.
crypt
The low-level crypt(3) one-way hash: the salt prefix selects the algorithm (DES/MD5/bcrypt/SHA-256/512) and the hash string is self-describing; demonstrates deterministic output with a fixed salt plus prefix identification - best practice is the password_hash wrapper.
hash
Generic hashing entry: computes a digest by algorithm name (e.g. sha256) and returns lowercase hex.
hash_algos
Returns the list of registered hashing algorithms in the current environment.
hash_equals
Timing-safe (constant-time) string comparison to prevent timing attacks — the mandatory way to compare MACs, hashes and tokens.
hash_hkdf
HKDF key derivation (RFC 5869: extract to a pseudorandom key, then expand to length) — pairs with hash_pbkdf2: slow PBKDF2 for passwords, fast HKDF for keys.
hash_hmac
Computes a keyed digest of a message with HMAC (Hash-based Message Authentication Code) using the given algorithm.
hash_pbkdf2
Runs PBKDF2 key derivation and returns the key at the requested length as hex or binary.
hash_update
Pushes data into a streaming hash context, allowing chunked feeding of large files without memory overhead.
hash_update_file
Streams a file into a running hash context (the file version of the hash_init three-step): constant memory, the standard way to digest large files; on failure it returns false and leaves the context usable.
md5
Computes the MD5 digest of a string as 32 lowercase hex characters (cryptographically broken; checksum uses only).
openssl_encrypt
Authenticated encryption with AES-256-GCM: a walkthrough of openssl_encrypt's tag/aad parameters ($passphrase is really the raw key); failed verification makes openssl_decrypt return false.
Asymmetric Sign & Verify
RSA PKCS#1 v1.5 sign and verify: with a fixed key the signature is deterministic (SHA-256 digest + deterministic padding) and byte-identical across implementations. Alongside Ed25519 (sodium_crypto_sign) it marks the two signature worlds — RSA vs modern curves.
password_get_info
Parses a password hash's prefix metadata (algo ID/algoName/cost...) without verifying the hash; this completes the password_hash/verify/needs_rehash/get_info quartet.
password_hash
Creates a one-way password hash (bcrypt by default: automatic random salt, deliberately slow); this entry demos the paired password_verify check on a fixed hash to keep output deterministic.
password_needs_rehash
Password-hash upgrade detection: the stored hash string is self-describing metadata (parse the $2y$12$ prefix) - rehash on login when the algorithm or cost no longer matches; the third piece of the password family.
password_verify
Checks whether a password matches the hash string produced by password_hash, returning true/false.
sha1
Computes the SHA-1 digest of a string as 40 lowercase hex characters (broken by practical collision attacks; not for security).
Authenticated Public-Key Encryption
Public-key encryption (X25519 key agreement + XSalsa20-Poly1305): the sender encrypts with the recipient's public key and only the matching private key decrypts. The counterpart to symmetric secretbox — box = key agreement + secretbox.
sodium_crypto_ipcrypt_*
Reversible IP-address encryption (new in PHP 8.6, Sodium): the ipcrypt spec's four modes — deterministic (single AES block, same input same ciphertext), nd (random nonce), ndx (extended nonce), pfx (prefix-preserving) — de-identified logs that stay traceable.
Argon2id Password-Derived Keys
Derive a key from a password (Argon2id, memory-hard): with a fixed salt and parameters the derived key is deterministic and interoperable. A triangle with PBKDF2 (hash_pbkdf2) and bcrypt (password_hash) — memory hardness is the modern bar.
sodium_crypto_secretbox
Authenticated encryption with a shared key: XSalsa20-Poly1305 produces a 16-byte MAC followed by the ciphertext; decryption returns false when the tag does not verify.
Streaming AEAD
Streaming AEAD for large files: one 24-byte header plus per-chunk push/pull, each chunk carrying a tag (MESSAGE/FINAL/PUSH/REKEY), state evolving with the ciphertext — tamper any chunk and the stream dies. The counterpart to one-shot secretbox.
sodium_crypto_sign
Ed25519 digital signatures (deterministic: same key and message always produce the same signature); returns signature || message, and failed verification surfaces as sign_open returning false.
sodium_crypto_xof_shake256
SHAKE256 extendable-output function (new in PHP 8.6, Sodium): squeeze any output length on demand from the same input; length comes first.
sodium_crypto_kem_*
Post-quantum key encapsulation (new in PHP 8.6, Sodium): an X-Wing hybrid family (ML-KEM-768 + X25519) and a pure-PQ ML-KEM-768 family (FIPS 203) with identical workflows — enc produces [ciphertext, shared secret], dec recovers the same secret.
abs
Returns the absolute value of a number.
base_convert
Arbitrary-base string conversion (2-36 both ways); large numbers lose precision through the internal float (manual warning, verified) - use BCMath/GMP for exactness.
bindec / octdec / decbin / dechex / hexdec (fixed-base quick reference)
Quick reference for the fixed-base conversions between binary/octal/hexadecimal and decimal: bindec/octdec/hexdec parse to decimal, decbin/dechex format from decimal. For arbitrary bases (2-36) see the base_convert entry; the single-function deep dives live in the dechex/hexdec entries.
ceil
Rounds fractions up (ceiling).
clamp
Range clamping (new in PHP 8.6): returns the value when it lies within [min, max], otherwise the nearest bound; min > max throws ValueError.
dechex
Converts a decimal number to its hexadecimal string representation.
deg2rad / rad2deg
Converts between degrees and radians: deg2rad multiplies by pi/180 and rad2deg by 180/pi — the two-way bridge in and out of trigonometric functions.
the exp / log / log10 / log1p family
The transcendental family: exp/log are mutual inverses (log(exp(2)) returns 2), log10 is the common logarithm, and log1p computes log(1+x) accurately even when x is near zero — the contrast experiment "1 + 1e-16 rounds to exactly 1.0 in double" is the heart of this entry.
fdiv
Safe float division (PHP 8.0+): division by zero and invalid input don't throw DivisionByZeroError — IEEE semantics return INF/-INF/NAN.
floor
Rounds down toward negative infinity: floor(-2.5) is -3 while an int cast truncates toward zero giving -2 - the negative-direction trap is the core teaching point paired with ceil.
fmod
Float modulo whose result keeps the sign of the dividend.
hexdec
Converts a hexadecimal string to a decimal number.
hypot
Calculates the hypotenuse of a right-angle triangle (distance from (x, y) to the origin). Mathematically equal to sqrt(x^2+y^2), but it scales before squaring so intermediate values never overflow — the extreme 3e200/4e200 contrast is the heart of this entry: the naive formula squares its way to INF while hypot still returns 5e200.
is_infinite
Checks whether a value is infinite (INF or -INF).
is_nan
Checks whether a value is NaN (not a number).
max
Returns the largest of several values.
min
Returns the smallest of several values.
mt_rand
Mersenne Twister pseudo-random integers: once mt_srand fixes the seed the sequence is fully reproducible — the only randomness entry whose output can be pre-set deterministically.
pow
Raises a number to a power (PHP 8 recommends the `**` operator).
rand
Generates a random integer within a given range.
random_bytes
Generates cryptographically secure random bytes (for tokens, keys, salts and the like).
random_int
Generates a cryptographically secure random integer (both bounds inclusive).
round
Rounds a float to a given precision.
sqrt / pi
Square root and pi: sqrt returns the float square root (negative input yields a silently propagating NAN, not an error), and pi() holds the same double-precision pi as the M_PI constant; under IEEE 754 every language's output matches exactly.
the sin / cos / tan family
Quick reference for the trigonometric family: basic (sin/cos/tan), inverse (asin/acos/atan) and hyperbolic (sinh/cosh/tanh) functions are built in across all languages — and every argument is in radians, not degrees; convert with deg2rad first.
bcadd
Adds two arbitrary-precision number strings and returns the result as a string.
bccomp
Compares two arbitrary-precision number strings and returns -1, 0 or 1.
bcdiv
Divides two arbitrary-precision number strings, truncating to the scale decimal places.
bcmod
Modulo of arbitrary-precision integers: operands and the result are number strings; a zero modulus throws DivisionByZeroError in PHP 8.
bcmul / bcsub
Completing the bcmath arithmetic family (alongside the existing bcadd/bcdiv/bcmod/bcpow/bcscale/bccomp) — strings in, strings out, with scale truncating decimal places; counterparts are BigDecimal/Decimal/big integers across languages, hand-written schoolbook arithmetic where absent.
bcpow
An arbitrary-precision number raised to an integer power: results like 2^64, far beyond the int range, come back exactly as strings.
bcscale
Sets the global default scale (decimal places) for the bcmath family, effective when a scale argument is omitted; returns the previous scale since PHP 8.
intdiv
Integer division: the quotient truncates toward zero; dividing by zero throws DivisionByZeroError.
cal_days_in_month
Days in a month under a given calendar (calendar extension): CAL_GREGORIAN applies the Gregorian leap rule — divisible by 4 but not 100, or divisible by 400, gives February 29; 2024-02=29 vs 2023-02=28 is the canonical leap-year teaching sample, with 2000/1900 completing the century rules.
checkdate
Validates a Gregorian date.
date
Formats a timestamp into a date string according to a given format.
date_create
Creates a DateTime object (the functional twin of new DateTime; returns false instead of throwing on parse failure).
date_create_from_format
Parses a date string against an explicit format (the functional twin of DateTime::createFromFormat), in contrast to strtotime's free-form parsing — format letters match positionally, overflowing dates are normalized with warnings, and hard errors return false.
date_create_immutable / date_create_immutable_from_format
Immutable date objects (DateTimeImmutable): modify returns a new instance and the original never changes — versus the mutable DateTime; java.time/datetime/time.Time share the philosophy across languages, with JS Date as the mutable exception that must clone to protect itself.
date_default_timezone_set
Sets the default timezone used by all date functions in the script.
date_diff
Computes the difference between two dates, returning a DateInterval.
DateTime::modify
Modifies a date with natural-language relative modifiers ('+1 day', 'next Thursday', '-2 months') — the only mainstream date object with this built in; its month-end overflow semantics differ sharply from the explicit arithmetic of other languages.
date_parse
Leniently parses a date string into a field array (no format needed); failure still returns an array - an odd interface that reports via error_count/errors, contrasted with date_create_from_format's strict-format route.
date_parse_from_format
Parses a date with an explicit format into a field array (with error_count/errors locating character positions) — contrasted with date_create_from_format (returns an object) and date_parse (free-form parsing); strptime/DateTimeFormatter are the language counterparts.
date_sun_info
Returns sunrise/sunset/transit and twilight boundaries as a timestamp array for given coordinates and date (astronomically fixed); it replaces the 8.1-deprecated date_sunrise/date_sunset; polar edges fill with bool.
DateTime::getTimestamp
Converts between a DateTime object and Unix epoch seconds: getTimestamp reads the epoch (date_timestamp_get is its functional twin) and setTimestamp writes it back; contrasted with the seconds-vs-milliseconds API families of other languages.
date_timezone_set / date_timezone_get
Zone-object read/write: date_timezone_set switches a DateTime instance's zone (the instant never moves; only the representation view changes) and date_timezone_get reads it back; contrast with date_default_timezone_set's process-wide default — object-level settings never pollute the global.
DateInterval
A date-interval/duration object: produced by DateTime::diff for the difference between two dates, or constructed manually from an ISO 8601 duration string (e.g. P2D, PT2H30M).
DatePeriod
A date-range iterator: walks a series of dates given a start, an interval and an exclusive end, usable directly in foreach.
DateTime
The object-oriented date-time class (since PHP 5.2): a unified entry point for parsing, formatting, relative modification and interval math, sharing the same engine as the functional date()/strtotime().
getdate / gmdate
A pairing of the structured date array and always-UTC formatting: getdate returns every field at once (seconds/minutes/hours/mday/wday/mon/year/yday/weekday/month, in local-time semantics), while gmdate formats in UTC regardless of the default timezone (date() follows the default timezone instead).
hrtime
High-resolution monotonic timing: hrtime() returns a [seconds, nanoseconds] array and hrtime(true) a plain nanosecond integer. A monotonic clock only advances - NTP adjustments and DST touch the wall clock only, so use this for timing code and microtime for timestamps.
microtime
Returns the current Unix timestamp (a 'microsec sec' string by default, a float in seconds when passed true).
mktime
Builds a Unix timestamp from year, month, day, hour, minute, and second.
strtotime
Parses a date/time string into a Unix timestamp.
time
Returns the current Unix timestamp in seconds.
timezone_identifiers_list
Returns every IANA timezone identifier the environment can pick from (procedural alias of DateTimeZone::listIdentifiers), filterable by DateTimeZone::ALL/AFRICA/AMERICA/… groups or PER_COUNTRY plus a country code; pairs with date_timezone_set_get's "set a zone" side — list first, then set.
json_decode
Parses a JSON string into a value.
json_encode
Serializes a value into a JSON string.
json_encode flags
Common json_encode flags: JSON_PRETTY_PRINT for pretty printing, JSON_UNESCAPED_UNICODE to keep CJK raw, JSON_UNESCAPED_SLASHES to keep slashes raw.
json_last_error
Returns the error code of the most recent JSON encode/decode operation.
json_last_error_msg
Turns the error code of the most recent JSON operation into a human-readable English message; pairs with json_last_error.
json_validate
Checks whether a string is syntactically valid JSON (PHP 8.3+, without building the value).
PCRE pattern modifiers (i/m/s/x/u/D)
A semantics table for PCRE modifiers — i (case), m (line anchors), s (dot-all), x (free-spacing), u (UTF-8), D (strict $) — and how each language's flag system maps to them.
preg_filter
Performs a preg_replace-style substitution but returns only the elements that were replaced — on arrays it is filter-and-replace in one.
preg_grep
Returns the array elements that match a pattern (original keys preserved).
preg_last_error
Returns the error code of the most recent PCRE failure.
preg_match
Searches a string for a match using a regular expression.
preg_match_all
Searches a string for all matches of a regular expression (not just the first) and returns the match count.
preg_quote
Escapes the special characters in a regular expression.
preg_replace
Replaces matches in a string using a regular expression.
preg_replace_callback
Finds every match of a regular expression and calls a callback to compute the replacement text for each.
preg_replace_callback_array
Runs a regex substitution with one callback per pattern (PHP 7+), handling many token kinds in a single call instead of stacked preg_replace_callback calls.
preg_split
Splits a string using a regular expression as the delimiter.
ctype_digit
Checks whether every character of the string is a decimal digit 0-9 (narrow ASCII semantics); entry point of the Ctype character-checking family.
the ctype_* family
Aggregate of the other nine ctype functions: alnum/alpha/lower/upper/space/xdigit/graph/print/punct, all narrow-ASCII; compared with each language's ASCII-narrow and Unicode-wide schools (ctype_digit has its own entry).
filter_input
Fetches a variable by name from a superglobal input source with optional filtering: INPUT_GET/POST/COOKIE/SERVER/ENV/REQUEST constants pick the source, FILTER_VALIDATE_*/SANITIZE_* pick the filter. It reads the SAPI's ORIGINAL input, not your modified superglobal copy; unset returns null, filter failure returns false (FILTER_NULL_ON_FAILURE swaps the semantics). Under CLI, GET/POST/COOKIE are always null - an honest environment-independent demo.
filter_var
Validates or sanitizes a value with a built-in dictionary of filters: the FILTER_VALIDATE_* family validates (false on failure, or null with FILTER_NULL_ON_FAILURE), the FILTER_SANITIZE_* family sanitizes - PHP's unique "validation dictionary" ecosystem.
get_debug_type
Returns a variable's real type name (PHP 8.0+): float/int/stdClass, contrasted with gettype's historical double/integer - always prefer it for debugging.
intval / floatval / strval / boolval
The four explicit conversion functions. Trap table: intval('123abc')=123 (prefix parsing), boolval('0')=false (the only falsy string), all equivalent to the (int)/(bool) operators.
is_array
Finds whether a variable is an array.
is_bool
Finds whether a variable is a boolean.
is_callable
Verifies whether a value can be called as a function in the current scope (a closure, a function-name string, or an [object, method] array).
is_countable
Checks whether a value can be counted with count() (array or Countable, PHP 7.3+). Contrasts the everything-has-length camp (len()/length asks the object directly) with the explicit-interface camp (count requires Countable).
is_float
Exact float-type check: true only for the float type - int is a different type and numeric strings stay strings (is_numeric tests those); is_double is an alias.
is_int
Finds whether a variable is of integer type.
is_iterable
Checks whether a value can be traversed with foreach (array or Traversable, PHP 7.1+). Contrasts three camps: Python/JS protocol style, Go/Rust compile-time style, Java/C# interface style.
is_null
Finds whether a variable is null.
is_numeric
Finds whether a variable is a number or a numeric string.
is_scalar / is_object / is_resource
Scalar/object/resource triple check rounding out PHP's type system: scalar = bool/int/float/string; resource is unique to PHP (an external handle), matched elsewhere by Closeable, FILE*, OwnedFd and friends.
is_string
Finds whether a variable is a string.
get_resource_type / get_resource_id / get_resources
Resource introspection: get_resource_type reads the handle's type name (e.g. stream), get_resource_id its numeric id, and get_resources lists currently live resources (optionally filtered by type; debugging tool).
settype
Changes a variable's type in place (bool/int/float/string/array/object/null...) - the by-reference conversion is the odd one out: every other language returns a new value with types fixed.
basename
Returns the trailing name component of a path.
chmod / chown
Changes a file's permission bits and owner: chmod sets rwx bits with an octal mode (the leading 0 is mandatory), chown changes the owner (only the superuser may give a file away); PHP's own chmod clears that path's stat cache — clearstatcache is needed for changes made OUTSIDE the process.
clearstatcache
Clears PHP's per-path cached file status (the stat family): long-running processes need it before re-querying a path changed externally; modern PHP already auto-invalidates most in-script writes.
dirname
Returns the directory portion of a path with the trailing name component removed.
disk_free_space
Returns the bytes free on the filesystem or partition holding the directory as a float, false on failure; disk_total_space supplies the total.
fgetcsv / fputcsv
The CSV read/write pair: fputcsv writes with RFC 4180 quoting rules and fgetcsv parses back; escape must be passed explicitly since 8.4 (empty string recommended); the quoted-comma/newline/doubled-quote traps are shown with an in-memory round trip.
fgets
Line-by-line reading: PHP fgets keeps the trailing newline in the return value (length-1 cap) and returns false at EOF - whether each language keeps the newline is the core teaching point.
file
Reads an entire file into a line array (newlines kept by default, stripped with FILE_IGNORE_NEW_LINES) - the array counterpart of file_get_contents' single string: pick file() for line-by-line work and file_get_contents for whole-text handling.
file_exists
Checks whether a file or directory exists.
file_get_contents
Reads an entire file into a string.
copy / rename / unlink
The three file operations: copy (silently overwrites the destination), move/rename (rename also works on whole directories), and delete (unlink removes a symlink itself); all three return bool.
file_put_contents
Writes a string to a file and returns the number of bytes written.
fileatime / filectime / fileowner / filegroup / fileinode
File metadata family: fileatime/filectime/fileowner/filegroup/fileinode read access time, inode-change time, owner/group and inode; together with filemtime/fileperms/filesize they complete the full stat family. Results are cached per path; failures return false.
filemtime
Returns the file's last modification time (mtime) as Unix epoch seconds, or false on failure; cached per path, so clearstatcache before re-reading.
fileperms
Returns the file's full access mode (including file-type bits, e.g. octal 100644); ANDing with 0777 extracts the plain permission bits. False on failure.
filesize
Returns the file size in bytes (false on failure); results are cached per path, so clearstatcache before re-reading.
finfo_open / finfo_file / mime_content_type
MIME type detection: finfo_open builds the detector, finfo_file classifies by header magic bytes (filename-independent), mime_content_type is the one-step shorthand; backed by the libmagic database, unknown magic yields a generic default instead of an error.
flock
Applies an advisory lock to an open stream: LOCK_SH shared read / LOCK_EX exclusive write / LOCK_NB non-blocking / LOCK_UN release - the classic tool for multi-process write safety.
fopen
Opens a file and returns a stream handle (resource) that the whole f* family operates on; complements the fopen_modes concept entry - this entry focuses on the handle you get back.
fopen (mode family: r/r+/w/w+/a/a+/x/x+)
Opens a file per a mode string — the 8 modes decide four semantics (read/write, existence policy, truncate-on-open, forced-append); every language has its own open-mode vocabulary.
fpassthru / readfile
Two engines for dumping files: readfile writes the whole file to the output buffer in one step and returns the byte count; fpassthru streams from the stream's current position to EOF - the memory-difference teaching point for large downloads.
fread / fwrite
Block read/write: fread reads up to length bytes and fwrite returns the bytes actually written - both can come up short, so loop-until-full-or-EOF is the cross-language streaming idiom.
fscanf
Parses fields from a file stream by a format string: the file-stream sibling of sscanf (sscanf covered in A24); without by-reference variables it returns the parsed array, and false at EOF; the return-value semantics (assigned-field count) align with the C fscanf family.
fseek / ftell
Random access: SEEK_SET/CUR/END whences paired with ftell - the basics of jumping around large files and locating in logs; SEEK_END needs a NEGATIVE offset to land before the end of file.
fstat / lstat
Fetches the whole stat field set in one call (fstat from an open handle, stat/lstat from a path): the full size/mode/mtime/ino/nlink family; lstat does NOT follow a symlink (it reports the link itself: size = length of the stored target path) while stat follows — the closing entry for the earlier fileperms/filesize/filemtime single-field trio.
fsync / fdatasync
PHP 8.1 forced durability: pushes buffered writes to the storage medium - fsync covers data AND metadata, fdatasync data only (POSIX-only; on Windows fdatasync is aliased to fsync); true means the data hit the medium.
ftruncate
Truncates or extends an open stream to a given length in place: shrink — bytes past the offset are dropped; grow — the file becomes larger and the new gap reads back as zero bytes (a sparse file). Combined with fseek+fwrite this is the common in-place rewrite pattern.
getimagesize
Image size detection: reads the file header (e.g. the PNG IHDR chunk) for width/height/MIME without decoding the whole image and without requiring GD — hand-rolled header parsing is the shared soul of the ten-language demo.
is_readable
Whether a file/directory exists and is readable (real UID/GID check, stat-cached); the family also has is_writable/is_executable.
link / symlink / readlink
A hard link is a second name for the SAME inode (nlink grows; deleting one name keeps the data), a symlink is a pointer holding a path string; readlink reads the stored target WITHOUT following; the classic dangling-link contrast: is_link and readlink succeed while file_exists (following semantics) is false.
move_uploaded_file
Moves an HTTP-uploaded temp file to a new location: it embeds the "must be a genuine upload" check (defeats forged tmp_name path attacks) and overwrites an existing destination; in the CLI SAPI there is no upload mechanism, so both this and is_uploaded_file always return false (the example demonstrates exactly that).
parse_ini_file
Parses an INI config file into an associative array: process_sections nests by section, INI_SCANNER_TYPED preserves bool/int types, and failure returns false.
pathinfo
Returns information about a path: directory name, file name, extension, and more.
realpath
Returns the canonicalized absolute pathname, resolving symlinks and . / .. components; the path must actually exist.
stream_copy_to_stream
Copies from $from's current position (seeking first when offset > 0) to EOF, capped by length, returning the byte count — large files need zero manual buffering (an internal chunked loop), and it is the native counterpart of Go's io.Copy.
stream_filter_append
Stream filter chains: attaches named filters (string.toupper, convert.base64-encode, ...) to a stream's read or write chain so all subsequent reads/writes are transformed automatically (read chain = transform on the way in, write chain = transform on the way out) — a PHP-unique stream decoration mechanism; mode can force READ/WRITE/ALL.
stream_get_contents
The handle-level "read to end": reads from the stream's current position to EOF (the counterpart of file_get_contents, which reads a whole path at once); length caps the bytes and offset seeks first.
stream_get_meta_data
Stream metadata: returns the stream's "dossier" — timed_out/blocked/eof/unread_bytes/stream_type/wrapper_type/mode/seekable/uri (plus crypto on TLS streams); "a stream is a resource, and a resource has a dossier" — the first tool for diagnosing timeouts and wrapper behaviour.
sys_get_temp_dir
Returns the temporary-file directory path (resolving the TMPDIR/TEMP/TMP environment family). The demo prints derived facts only - the path itself is environment-dependent, so it verifies "non-empty and absolute" instead.
tempnam
Temp-file naming: atomically creates a unique zero-byte file in the given directory (O_EXCL guards the TOCTOU race, mode 0600 on Unix) and returns the full path; the prefix is only a hint (first 63 chars, first 3 on Windows), with silent fallback to the system temp dir when the target is unwritable.
tmpfile
Creates an anonymous w+b temp file handle that is auto-deleted on fclose or script end - made for burn-after-use buffering and swap scenarios.
umask
Reads or sets the process permission mask: a new file's default mode is 0666 & ~umask; passing a mask sets it and returns the old one, omitting it only queries (complementary to chmod on existing files).
chdir
Changes the process working directory to the given path (relative paths resolve against the current one).
dir
The directory object (Directory class: dir() → read() loop → close()) — OOP directory traversal forming three read paradigms with readdir (procedural) and scandir (one-shot materialization); read returns unsorted entries including . and ..
getcwd
Returns the absolute path of the process working directory.
glob
Matches paths in a directory against a shell wildcard pattern, returning a sorted array.
is_dir
Tells whether the given filename is a directory.
mkdir
Creates a directory, optionally creating missing parent directories recursively.
readdir
Reads one entry at a time from a directory handle (streaming, memory-friendly for huge directories); omitting the handle argument is deprecated since PHP 8.5.
rmdir
Removes an empty directory.
scandir
Lists files and directories inside the specified path.
bzopen / bzread / bzcompress
The bzip2 family: bzopen/bzread/bzwrite stream .bz2 files while bzcompress/bzdecompress handle strings; built on the BWT (Burrows-Wheeler Transform) algorithm — a better compression ratio than gzip/deflate at the cost of speed.
deflate_init / deflate_add / inflate_init / inflate_add
Incremental (streaming) deflate compression/decompression: feed data in chunks with flush modes controlling block boundaries — contrasted with the existing gzdeflate (one-shot): NO_FLUSH middle chunks produce identical output while SYNC_FLUSH inserts sync-marker bytes; Python's zlib.compressobj and Java's Deflater are the direct counterparts.
gzcompress
Compresses a string in bare zlib format (RFC 1950): a 2-byte header, deflate data and an Adler32 trailer — no gzip wrapper.
gzdecode
Decompresses gzip (RFC 1952) data and returns the original string after CRC32 verification; false on failure.
gzdeflate / gzinflate
Compresses/decompresses raw deflate data (RFC 1951) — the leanest of the three zlib formats (raw deflate / zlib / gzip), forming a family with gzcompress (zlib format) and gzencode (gzip format); the wbits window parameter is the core switch across languages.
gzencode
Compresses a string in gzip format (RFC 1952); level 0-9 controls compression (0 = stored, no compression).
gzopen / gzread / gzwrite
Opens a .gz file pointer for streaming I/O: writes are compressed and reads transparently decompressed; the level can be embedded in the mode (e.g. "wb9") — suited for chunked processing of large files.
gzuncompress
Decompresses bare zlib (RFC 1950) data and returns the original string after Adler32 verification; false on failure.
ZIP Archive
ZIP in three steps: create (multi-file packaging that keeps directory structure), list entries, extract and read back. Contrast with gz/bz2 single-file compression — an archive is a container for many files plus directory structure.
checkdnsrr
Checks whether a host has DNS records of a given type (A/MX/NS/TXT, ...), returning true when found — the existence check of the DNS trio.
dns_get_record
Fetches DNS records (A/MX/NS/SOA, ...) for a hostname and returns the record array.
fsockopen
Low-level TCP/Unix socket client: returns a stream resource on success (fwrite/fgets/fclose apply) or false with errno/errstr filled on failure.
get_headers
Sends a request to a URL and returns the response headers as an array (the first element is the status line) — the built-in lightweight HTTP probe.
gethostbyname
Resolves a hostname to its IPv4 address string; on failure it raises no error and returns the hostname unchanged.
gethostname
Gets the local host name: CI and local machines necessarily differ, so the deterministic strategy prints only derived facts (success + non-empty), never the name itself.
getmxrr
Queries a host's MX mail-exchange records, filling the hosts and weights arrays by reference.
getprotobyname / getprotobynumber / getservbyname / getservbynumber
Protocol/service-name queries: forward and reverse lookups into the /etc/protocols and /etc/services system tables (decades-stable IANA values like tcp=6 and http=80/tcp); unknown names return false. getservbynumber is missing in some PHP builds (see notes).
header
Sends a raw HTTP response header: with setcookie and http_response_code it completes the web response control trio; must be called before any output, and is a silent no-op under CLI where headers_list() is always empty.
http_build_query
Serializes an array (nested ones included) into a URL-encoded query string, the inverse of parse_str; spaces are encoded as + by default.
http_get_last_response_headers
Returns the indexed array of headers from the most recent HTTP-wrapper response (first entry is the "HTTP/1.1 200 OK" status line), or null if there were none. Added in PHP >= 8.4.0 as the replacement for the implicit $http_response_header variable deprecated since 8.4. Under CLI no HTTP request has ever been made, so it is always null - an honest environment-independent demo.
http_response_code
Sets or gets the HTTP response status code; under CLI getting returns false and setting is a no-op (the same Web/CLI SAPI split as setcookie).
inet_ntop / inet_pton
IP text/binary conversion: inet_pton packs (4 bytes for IPv4, 16 for IPv6) and inet_ntop expands back - while ip2long is IPv4-only, this pair covers both stacks; invalid input returns false.
ip2long / long2ip
Converts a dotted-decimal IPv4 string to a 32-bit unsigned integer and back (ip2long to int, long2ip to string).
parse_str
Parses a URL query string into an array (the second argument is mandatory since PHP 8.0); dots and spaces in keys are converted to underscores.
parse_url
Parses a URL and returns its components.
pfsockopen
Persistent sockets: identical signature to fsockopen, the only difference being connection lifetime — after closing, the handle returns to a process-level persistent pool for same-process reuse (scope decided by the SAPI; on CLI the pool dies with the process); failures return false with errno/errstr filled.
Io\Poll
New in PHP 8.6: epoll/kqueue/event-ports/WSAPoll-grade I/O multiplexing — breaks past stream_select's 1024-descriptor ceiling and returns readiness as Watcher objects; wait takes a Time\Duration outright.
rawurldecode
Decodes a percent-encoded string, keeping plus signs (+) literal.
stream_context_create
Creates a stream context — the foundation for advanced file_get_contents/fopen network usage: preset HTTP method, headers, timeout, user-agent and more in a ['wrapper']['option'] nested array, which every stream call taking $context then inherits.
stream_select
I/O multiplexing — the direct descendant of C select(2): watches the read/write/except stream sets until any become ready or the timeout expires; returns the number of ready streams (0 = timeout, false = error, so test with === false), and rewrites the three arrays in place into the ready subset.
syslog
Sends a message to the system logger (LOG_INFO-style priority constants combined with the openlog facility); always returns true, the destination is up to syslog.conf/journald, and sending never crashes under CLI.
URI Builders
The PHP 8.6 URI builder family: UriBuilder stores only overrides and build() rebases onto an existing URI — completing the parse↔build pair with parse_url/http_build_query; the coexistence of RFC 3986 and WHATWG is the teaching core.
escapeshellarg
Escapes a string into a safe single shell argument (against command injection).
exec
Executes an external command and captures its output (via the shell, returning the last line).
passthru / escapeshellcmd
passthru streams the child output straight through (no return string, fit for binary data); escapeshellcmd escapes metacharacters in a command string in place, complementing escapeshellarg's "wrap the whole value in quotes" - escaping functions exist precisely because PHP goes through the shell by default.
popen / pclose
One-way process pipes: popen opens a unidirectional pipe to a child process ("r" reads its stdout, "w" writes to its stdin) whose pointer works with fgets/fwrite; pclose closes the pipe, reaps the child and returns its termination status — the direct descendant of Unix popen(3), complementing proc_open's two-way pipes.
pcntl_fork
Unix process forking (PCNTL extension, unavailable on Windows builds): the return value is the identity — the parent gets the child PID, the child gets 0; pair every fork with a waitpid reap to avoid zombies.
proc_get_status / proc_close / proc_terminate
The proc_open trio: proc_get_status polls the child's state (running/exitcode/stopped), proc_close blocks to reap and yields the exit code, proc_terminate sends a kill signal - stopping and reaping are two steps, kill first then reap.
proc_open
Spawns a child process with bidirectional pipes: descriptor_spec maps fd 0/1/2, $pipes receives PHP-side handles, proc_close reaps - the only exec-family function with two-way I/O.
shell_exec
Executes a command via the shell and returns the full output as a string (equivalent to the backtick syntax).
system
Executes an external command and streams its output straight to this process's stdout (returning the last line).
extension_loaded / get_loaded_extensions
Extension introspection: extension_loaded probes one extension by name (compiled in or shared-loaded), get_loaded_extensions lists every loaded extension; mirrors hash_algos' inventory-consumer pattern — probe before use is step one of portable PHP.
ini_get
Reads a runtime config directive; returns a string ("0"/"1" for boolean switches) or false when the directive doesn't exist.
ini_get_all
Fetches all (or one extension's) runtime config directives at once; each item carries global value, local value and modification access.
ini_parse_quantity
PHP 8.2+: parses an ini shorthand value into bytes (the same parser behind memory_limit="128M"); k/M/G suffixes plus 0x/0b/0o/leading-0 bases; unparseable input or an invalid suffix raises E_WARNING and returns a best-effort value.
ini_set
Modifies a runtime config directive and returns its old value; only PHP_INI_ALL directives can change, false when it can't.
php_ini_loaded_file / php_ini_scanned_files
Config-file path introspection: php_ini_loaded_file returns the full path of the php.ini this process actually loaded (false when none), php_ini_scanned_files returns the comma-separated list of additional ini files parsed from the scan directory (configure --with-config-file-scan-dir) or false; pairs with ini_get — path introspection answers "where values come from", ini_get answers "what the values are".
php_sapi_name
Returns the lowercase name of the hosting interface (SAPI) - "cli", "fpm-fcgi", "apache2handler", etc.; the PHP_SAPI constant holds the same value, letting one script tell its CLI and web forms apart.
php_uname
System identity: modes 's'/'n'/'r'/'v'/'m' mirror the POSIX utsname fields sysname/nodename/release/version/machine; with no argument it returns the five glued together. Use PHP_OS_FAMILY for a simple OS-family check.
phpinfo
Dumps a full introspection report of the current PHP (config, extensions, env vars, license, ...), section-selectable via INFO_* constants.
set_time_limit
Resets the script's maximum execution time in seconds (the counter restarts at the call); 0 means unlimited; on timeout the script is terminated with a fatal error.
version_compare
Compares two version strings numerically, recognizing dev/a/b/RC/pl/p suffixes; with a third operator argument it returns a bool directly.
call_user_func
Invokes a callback (call by name; closures work the same way).
call_user_func_array
Invokes a callback with arguments unpacked from an array (the classic entry point for variadic calls).
func_get_args
Collects every argument the current function actually received (the pre-5.6 standard for hand-rolled variadics): even extras beyond the declared parameters are kept; modern code declares ...$args instead, and the two behave identically.
func_num_args
Returns the number of arguments passed to the current function (pairs with func_get_args for variadic handling).
function_exists
Checks whether a function is defined by name (a common tool for extension checks and feature detection).
get_defined_functions
A snapshot of the process function table: internal (builtins) and user (script-defined) halves - the memory-introspection pair of get_defined_vars.
spl_autoload_functions
Returns the SPL autoloader registry: every callback pushed by spl_autoload_register, enumerable in registration order - registering writes it, this reads it.
class_exists
Checks whether a class is defined (or can be autoloaded); part of the family with interface_exists/enum_exists.
method_exists
Checks whether a method exists on a class or object.
property_exists
Checks whether a property exists on a class or object (including properties whose value is null).
ReflectionClass
Runtime introspection of a class: reads the class name, method list, and property list.
reflectionproperty_isreadable
Per-scope readability/writability checks (new in PHP 8.6, Reflection): factoring in visibility, asymmetric visibility, hooks, __get/__set and initialization state.
debug_backtrace
Returns the call-stack frames as an array (each frame carries function/line/file/class); IGNORE_ARGS drops args to save memory, limit caps depth.
debug_print_backtrace
Prints the current call stack directly (innermost frame first) - essentially debug_backtrace() rendered as #0.. text; supports DEBUG_BACKTRACE_IGNORE_ARGS and a frame limit.
debug_zval_dump
Dumps a variable's internal zval details (type, value, and reference count) — the debug window into PHP's copy-on-write machinery.
memory_get_peak_usage
The script's memory peak (a high-water mark that never decreases and is always >= current usage): pairs with memory_get_usage's current value; handy for spotting memory spikes in batch jobs.
memory_get_usage
Returns the amount of memory currently allocated to the script (actual use by default; true includes unused pages held by the allocator).
print_r
Prints a human-readable representation of a value (arrays/objects as indented trees), without type info.
var_dump
Dumps type, length and value of one or more variables — the most precise debug dump.
var_export
Outputs a valid PHP code representation of a value (re-loadable via eval/include), often for config export.
flush
Pushes the system write buffers of PHP and its backend (CGI/web server) toward the client; does not touch ob_start user-level buffers.
ob_end_flush / ob_flush
Two flush verbs: ob_flush pushes the active user buffer one layer down (frame stays open), ob_end_flush flushes and closes that frame; flush() pushes system-level buffers toward the client.
ob_get_clean
Returns the current buffer contents and ends buffering — equivalent to ob_get_contents plus ob_end_clean.
ob_get_length
Returns the byte length of the active output buffer, or false if buffering is off.
ob_get_level
Returns the current output-buffering nesting level: each ob_start pushes a frame, each ob_end_* pops one - nested buffers are a stack.
ob_implicit_flush
Toggles implicit flush mode; when enabled every output call flushes automatically.
ob_start
Turns on output buffering; subsequent output goes into a buffer instead of being sent directly.
$_COOKIE
Reads request cookies: under Web SAPI the Cookie request header is parsed automatically into the $_COOKIE array.
session_abort / session_reset
Two ways to drop session changes: session_reset reloads the stored values and keeps the session active; session_abort discards changes and closes the session. Together with session_write_close (commit) they form the read-modify-commit/rollback triad.
session_cache_limiter / session_cache_expire
Reads/sets the HTTP cache policy for session pages: the limiter decides which Cache-Control/Expires headers session_start sends (nocache/private/private_no_expire/public/off) and expire sets their max-age/Expires value in minutes; re-set each request before session_start.
session_create_id
Creates a collision-free session ID (charset [0-9a-zA-Z,-], optional prefix); the ID shape (length/charset) follows php.ini. Performs a collision check while a session is active — the companion tool for user-level save handlers.
session_decode / session_encode
Session-data (de)serialization: session_encode serializes $_SESSION into the internal format string (with the default handler, key names joined to serialize-encoded values by |), session_decode decodes and repopulates $_SESSION; decoding untrusted input is the same injection surface as unserialize.
session_destroy
Destroys the session data in storage (logout semantics); it does not clear the $_SESSION superglobal — clear it yourself.
session_gc
Runs one round of session garbage collection immediately (removing expired session data) and returns the number of deleted entries; a replacement for probabilistic gc_probability triggering, invoked from cron on busy sites.
session_id
Gets or sets the current session ID: calling without arguments returns the current session id, or the empty string when no session is active; passing an id replaces it (must be called before session_start()). Belongs to the session-fixation defense family together with session_regenerate_id(). The default files handler generates a 32-char lowercase-hex SID - the value is random and cannot be pre-set, so the demo asserts the format only.
session_name
Reads/writes the session cookie name (default PHPSESSID): must be set before session_start, and the return value is the OLD name - the opposite of intuition.
session_regenerate_id
Replaces the current session ID with a new one while keeping session data — the standard move in session fixation defense.
session_save_path
Reads/writes the storage directory of the built-in files handler; setting must happen before session_start(), and the setter returns the previous path (false when none was set). The storage-location switch short of session_set_save_handler.
session_set_cookie_params / session_get_cookie_params
Sets/reads the session cookie's security parameters (lifetime/path/domain/secure/httponly/samesite; 7.3+ options-array style); the effect lasts one request only and the call must run before session_start().
session_set_save_handler
Custom session storage: register a SessionHandlerInterface implementation (open/close/read/write/destroy/gc) to replace file storage - the official exit hatch for Redis/DB-backed sessions.
session_start
Starts the session (also sends the session cookie under Web SAPI); afterwards session data is read/written via $_SESSION.
session_status
Queries the three-state session machine: PHP_SESSION_DISABLED / NONE (enabled but not started) / ACTIVE (started) — the standard guard for idempotent session_start() calls.
session_unset
Empties all session variables in $_SESSION while keeping the session and its storage alive (unlike session_destroy, which removes the storage); equivalent to $_SESSION = [] and only works while a session is active.
session_write_close
Writes $_SESSION data to storage and ends the current session (releasing the write lock); later $_SESSION changes are not persisted.
setcookie
Queues a Set-Cookie response header (expiry/path/domain/HttpOnly/Secure are all header parameters); must be called before any output.
setrawcookie
Same Set-Cookie registration as setcookie, minus URL-encoding — the value goes into the header verbatim (fits base64/hashes/values already in a safe charset); values containing spaces/commas/semicolons are invalid at the HTTP layer.
assert
Asserts an expectation that should always hold; failure throws AssertionError; only zend.assertions=1 executes it, while -1 (recommended for production) compiles it away at zero cost.
error_clear_last
Clears the record of the most recent error.
error_get_last
Returns the most recent error that occurred (type/message/file/line).
error_log
Log routing: message_type sends to system logger (0) / email (1) / destination file append (3) / SAPI log (4); type=0 always returns true.
error_reporting
Sets which error levels are reported and returns the current level.
restore_error_handler
Removes the current error handler and restores the previous one.
set_error_handler
Registers a custom callback to take over error handling.
set_exception_handler
Installs the fallback handler for uncaught throwables (both Error and Exception implement Throwable); returns the previously installed handler (null if none); the script ends after the callback returns.
Structured Stream Errors
The PHP 8.6 stream error family: the error_mode context option turns stream failures into thrown StreamExceptions or silence — errors become structured objects of StreamErrorCode enum + wrapperName + path, ending the era of the warning string.
trigger_error
Raises a user-level error or warning from user code.
cli_set_process_title / cli_get_process_title
CLI process title read/write: cli_set_process_title rewrites the process name ps/top displays (giving each worker a recognizable identity), cli_get_process_title reads it back; the demo follows the "set, then set back" discipline — no residue left on the host process.
connection_status
Returns the connection status bitmask: CONNECTION_NORMAL(0)/CONNECTION_ABORTED(1)/CONNECTION_TIMEOUT(2), combinable bitwise (ABORTED|TIMEOUT=3). In Web scenarios it detects client disconnects; CLI has no HTTP client connection, so it is always CONNECTION_NORMAL - an honest environment-independent demo. Pairs with ignore_user_abort() as the connection-handling teaching closure.
Time\Duration
New in PHP 8.6: a nanosecond-precision duration — attached to no instant, no timezone, comparable and arithmetic-friendly; upgrades the bare millisecond numbers of sleep/usleep/time_nanosleep into a typed duration.
eval
A language construct that executes a string as PHP code: literal-expression evaluation is deterministic; feeding user input into eval is arbitrary code execution — the core risk lesson of this entry.
gc_collect_cycles
Forces collection of cyclic garbage and returns the number of objects collected. PHP memory management is refcounting plus periodic cycle detection; this function triggers one detection-and-sweep round immediately.
getopt
CLI option parsing: a short-option string (colon = takes a value) plus a long-option table (trailing '=' = takes a value), returning an option-to-value map. Its modern successors are frameworks like argparse/flag/clap.
getrusage
Per-process resource usage: user/system CPU time (ru_utime/ru_stime), peak resident memory (ru_maxrss) and 30+ fields; defaults to this process, RUSAGE_CHILDREN sums reaped children.
highlight_string
Built-in PHP syntax highlighting: highlight_string/highlight_file return <span>-colored HTML directly, no extension or third-party library needed — the only runtime-builtin highlighter among the ten languages.
ignore_user_abort
Read/set the "keep running after client abort" switch: null reads the current value, a bool sets it and returns the previous one (int 0/1); pairs with connection_status' bitmask — the status tells you whether the client left, this switch decides whether you keep going; CLI has no client, so get/set is pure switch read/write.
mt_srand / srand
Seeds the global Mt19937 engine (srand is its alias since 7.1): a fixed seed gives a fully REPRODUCIBLE sequence; the algorithm is pinned since 7.1, so the numbers are stable across versions and platforms.
pack / unpack
Binary data packing and unpacking: format letters pin both type and byte order (n/N big-endian, v/V little-endian, d/f floats, a/A strings) - the low-level tool for wire protocols and binary files.
Random\Randomizer
OOP randomness facade (PHP 8.2+): inject a seedable engine (e.g. Mt19937) at construction and every sequence from getInt/shuffleArray becomes exactly reproducible; without a seed it falls back to the cryptographically secure engine.
register_shutdown_function
Registers a callback to run after script execution finishes (or exit() is called), fired in registration order.
register_tick_function
Fires a callback every N low-level statements inside declare(ticks=N) - a PHP-only per-statement hook with no counterpart in other mainstream languages (the other entries here are hand-instrumented contrasts).
serialize / unserialize
Turns any PHP value into a portable string and back. The core security lesson: unserialize on untrusted input is object injection (triggering __wakeup/__destruct attack chains) - the allowed_classes whitelist is the only safe usage.
sleep
Pauses the script for a number of seconds (blocking the current execution flow).
sys_getloadavg
System load-average introspection: returns [1min, 5min, 15min] samples (Unix load = exponentially damped average of runnable plus uninterruptible tasks), false on failure; complements getrusage (process-level) — this one is machine-level; values float with machine state, so only the shape can be asserted.
time_nanosleep / time_sleep_until
The sleep family closure: time_nanosleep(seconds, nanoseconds) takes dual-integer args for precise delay (verified against the current php.net manual as NOT deprecated - a live page from PHP 5 through 8); a signal interrupt returns an array of remaining seconds/nanoseconds, so compare strictly with === true; time_sleep_until(timestamp) sleeps until a fixed moment, returning false with an E_WARNING for a past timestamp. Together with the sleep/usleep/hrtime family it forms a complete system.
token_get_all
Source tokenization: token_get_all splits PHP source into a token stream (T_ECHO/T_VARIABLE, etc.) using the Zend engine lexical scanner — the foundation of static analysis and code tooling.
uniqid
Generates a unique ID based on the microsecond timestamp (with optional prefix and extra entropy).
usleep
Delays script execution in microseconds (sub-second delays).
class_alias
Creates a runtime alias for a defined class (internal classes, interfaces and traits since 8.3) - the alias IS the same class, not a subclass.
class_implements / class_parents / class_uses
The SPL trio: the interfaces a class implements, its parent chain, and its traits, three lists in one family - the full-family portrait of inheritance relations.
enum_exists
Checks whether an enum is defined (may trigger autoloading); the enum sibling of class_exists/interface_exists/trait_exists, completing the PHP 8.1 type-table quartet.
forward_static_call
Forwards a static call down an inheritance chain while keeping late static binding (LSB): forward_static_call passes the "called class" along so static:: still resolves to the leaf subclass; a plain callback (call_user_func) falls back to the parent context.
get_called_class
Returns the class a static method was actually called on (late static binding); the functional form of static::class.
get_class
Returns the class of an object; the counterpart of instanceof - instanceof answers yes/no, get_class gives the exact name.
get_class_methods
Returns the public method names of a class or object (declaration order); the lightweight entry of the reflection family - a plain list without building a ReflectionClass.
get_declared_classes / get_declared_interfaces / get_declared_traits
Runtime class-table introspection: returns every class/interface/trait currently loaded (extension and builtin declarations included, user classes among them); no ordering guaranteed since 7.4; enums count as classes.
get_object_vars
Returns the object properties visible from the current scope - all three levels inside the class, public only outside; an object anatomy knife by visibility.
get_parent_class
Returns the parent class of an object or class, false at the root; makes the "one step up" of an inheritance chain a runtime-queryable fact.
interface_exists / trait_exists
Checks whether an interface or trait is defined (autoload may fire); part of the family with class_exists/enum_exists, a corner of PHP's runtime type table.
is_a
Checks whether an object (or a class-name string, when allowed) is of a given type or a subtype; prefer the instanceof operator for objects.
Simple XML Object Access
SimpleXML object-style XML handling: the document maps to an object tree you traverse with -> and property syntax, plus xpath queries. One of PHP's two XML philosophies alongside DOM — object access buys brevity, node operations buy control.
DOM Tree Parsing
DOM-style XML parsing: the whole document loads into an in-memory node tree with random access to any element, attribute or text node, and modifications serialize back to XML. One of the two big philosophies, opposite to streaming (XMLReader, see xmlreader_writer).
Streaming XML
Streaming-style XML: pull-based node-by-node reading (event driven, only the current node in memory, large-file friendly) and forward-only writing. Opposite to DOM loading the whole tree — the third XML philosophy.
Arrays (indexed/associative)
Demonstrates creating and reading indexed arrays and associative arrays (key-value pairs).
Asymmetric Visibility
Public to read, restricted to write — PHP 8.4 public private(set) against read/write splits in 10 languages.
Attributes and Annotations
How metadata is attached and who reads it — PHP 8 Attributes surveyed across 10 languages.
Autoloading
Demonstrates on-demand class loading; Go and Rust resolve everything statically at compile time and have no runtime autoloading.
Variables and types
Demonstrates variable declaration and basic data types: integers, strings, and floats.
Closures and anonymous functions
Demonstrates closures capturing outer variables; Java expresses them with lambdas, Rust through its three Fn capabilities.
Closure Binding
Who owns the call's context — Closure::bind against rebinding this/the receiver across 10 languages.
Constructor Property Promotion
Who writes the boilerplate for you — PHP 8.0 constructor promotion against parameter-to-field shortcuts in 10 languages.
Array Value Semantics and Copy-on-Write
What assignment actually does — PHP array value semantics and COW against array assignment in 10 languages.
Enumerations (Backed Enums)
PHP 8.1 backed enums: value/name/lookup versus enum models across 10 languages; Rust variants can carry data.
Exceptions (try/catch)
Throws and catches an exception, printing the caught message.
Fibers
Suspending the whole call stack or just one frame — PHP 8.1 Fiber against the concurrency-primitive spectrum of 10 languages.
First-Class Callables
Functions as values — PHP 8.1's `...` syntax against passing behavior as data in 10 languages.
foreach by Reference
as &$v writes straight into the array — PHP foreach by reference against traversal write-back in 10 languages.
Function definition and call
Defines a function that returns a string and calls it.
Generators
Demonstrates lazy sequence generation; Go approximates it with channels plus goroutines, Java with Streams, Rust with iterators.
Generators and Lazy Evaluation
Are values produced on demand or precomputed — PHP's lazy yield taught across 10 languages and four schools.
if/else conditionals
Demonstrates multi-branch conditionals with if / else if / else.
Integer Overflow
The outlier that promotes to float — PHP integer overflow surveyed against overflow strategies in 10 languages.
Lazy Objects
State initializes on first touch — PHP 8.4 lazy ghosts and proxies against deferred initialization in 10 languages.
Loops (for/foreach/while)
Demonstrates counting for loops, traversal loops (foreach/range/for...of), and while loops.
Magic Methods and Metaprogramming
Trigger paths of __get/__set/__call/__toString/__invoke, beside Python dunders, JS Proxy and Rust traits as metaprogramming entries.
match expressions
Compares switch and match; PHP match uses strict comparison, Rust match checks exhaustiveness at compile time.
Pattern Matching and Exhaustiveness
Expression or statement, exhaustive or not — PHP match surveyed across 10 languages on two dimensions.
Named Arguments
Position or name — PHP 8.0 named arguments versus how 10 languages pass parameters.
Namespaces and use
Demonstrates namespace organization and importing; each language maps the concept to modules or packages.
Namespaces and Module Systems
PHP namespace/use resolution and aliasing, surveyed against Go, Java, Rust, Python and JS module systems; links to spl_autoload_register.
Nullsafe Operator (?->)
Is null a type or a value — PHP ?-> chain short-circuiting beside C# ?., JS ?., Rust Option and Java Optional.
Operators
Demonstrates common operators: arithmetic, integer division, and modulo.
Partial Function Application
PHP 8.6's `?` placeholder — a call expression with holes returns a Closure that only runs once the remaining arguments arrive, contrasted with fixing some arguments in 10 languages.
Property Hooks
Properties whose reads and writes run code — PHP 8.4 property hooks against accessors across 10 languages.
Readonly Properties
The immutability spectrum — PHP 8.1 readonly versus how 10 languages block reassignment, and when.
Reference Variables
Is & an explicit alias or implicit sharing — PHP reference variables against the reference models of 10 languages.
String Value Semantics
Who changes after assignment — PHP string value semantics against string mutability in 10 languages.
String interpolation
Embeds variables into a string to build a complete sentence.
Typed Properties
Who catches the bad type first — PHP 7.4 typed properties against the core runtime-versus-compile-time check across 10 languages.
Union Types
Whether 'or' lives in the type or in the branches — PHP 8.0 union types against the type-system expressiveness of 10 languages.
Weak Maps
Whether entries follow the object or the map — PHP 8 WeakMap against GC-cooperative caching in 10 languages.
Abstract classes
Demonstrates abstract classes and methods; Go uses interfaces plus composition, Rust uses traits, JS relies on conventions.
Classes and instantiation
Defines a class with a constructor and methods, then instantiates and uses it.
Class constants
Demonstrates class-level constants; Python and JS have no true constants and approximate them with naming conventions and frozen objects.
Object cloning and copying
Distinguishes assignment by reference, shallow copy, and deep copy; Go and Rust express the same ideas with value semantics and explicit cloning.
Constructors and destructors
Demonstrates construction and destruction timing; Go and Rust replace language-level constructors with New/new convention functions.
Enums
Demonstrates enumerated types; Go simulates them with iota, JS with frozen objects, while Rust enums are the more powerful ADT.
Inheritance
Demonstrates inheritance and method overriding; Go expresses a similar effect with struct embedding and shadowing.
Type checking (instanceof)
Demonstrates runtime type checking; Go uses type assertions, Rust replaces it with enums plus pattern matching.
Interfaces
Defines an interface, implements it in a class, and computes the area of a rectangle.
Magic methods
Demonstrates property interception, dynamic invocation, and string conversion; each language approximates them with different mechanisms.
Properties and methods
Demonstrates private properties with methods that read and write them (encapsulation).
Static members
Demonstrates static properties and methods; Go substitutes package-level identifiers, Rust associated functions.
Traits
Demonstrates code reuse mechanisms; Python and JS use mixins, Go uses embedding, Java uses default methods.