Общие сценарии - примеры кода сообщества
Base62 Encoder for Short IDs
Encodes a non-negative integer to a compact base-62 string over 0-9a-zA-Z by repeated modulo and integer division, prepending digits. Decodes by scanning each char back through strpos on the alphabet. Good for short URL-safe slugs.
visibility129 виды
JSON Pointer (RFC 6901) Resolver
Walks a decoded JSON document by a slash-delimited pointer, unescaping ~1 to slash and ~0 to tilde in that order per the RFC, descending arrays by key and objects by property. Empty pointer returns the document, a missing segment throws.
visibility181 виды
Topological Sort with Kahn Algorithm
Builds an adjacency list and indegree map from a node-to-prerequisites graph, seeds a queue with zero-indegree nodes, then pops each, appends it, and decrements dependents. If fewer nodes come out than went in, a cycle exists.
visibility222 виды
LRU Cache in Pure PHP Using Ordered Arrays
Exploits PHP array insertion order: get() unsets and reappends the key so the most recently used sits at the tail, put() evicts via array_shift which drops the least recently used head when over capacity. Effectively O(1) amortized.
visibility83 виды
Human-Readable Byte Formatter and Parser
formatBytes derives the unit via floor(log(bytes,1024)), clamps to the unit table, and rounds value/1024^pow. parseBytes reverses it with a regex capturing the number and optional KB to PB suffix, then multiplies by 1024^index.
visibility156 виды
UUID v7 Generator (Time-Ordered) in Pure PHP
Builds a UUIDv7 by packing a 48-bit millisecond Unix timestamp into the first 12 hex chars, then 74 random bits from random_bytes, masking the version nibble to 7 and the variant bits to binary 10. Time-ordered so it indexes well as a primary key.
visibility45 виды
Finite State Machine (FSM) in Pure PHP
Stores current state and a transitions map keyed by [from_state][event]. trigger() looks up the next state, moves to it, appends to history, and fires the registered callback. on() accepts an array of source states for multi-origin transitions.
visibility22 виды
PHP 8.5 Property Hooks: Practical Examples
Defines get/set hooks on properties instead of __get/__set. The set hook validates and normalizes the value. Computed properties use only a get hook with no backing field. Also shows public private(set) asymmetric visibility.
visibility11 виды
Minimal Dependency Injection Container
A simple DI container with singleton and factory bindings, auto-wiring via reflection, and interface-to-class binding. Under 80 lines, no dependencies.
visibility10 виды
Deep Array Diff: Find All Changes Between Two Arrays
Merges keys from both arrays and checks each one. Missing in new = removed, missing in old = added, both arrays = recurse with dot-appended path, scalar mismatch = changed. Returns a flat map of paths to old/new values.
visibility11 виды
Parse .env File Without Any Library
Read and parse a .env file into an array or into $_ENV / getenv(). Handles comments, quoted values, multiline strings, and variable interpolation.
visibility12 виды
Circuit Breaker Pattern in Pure PHP
Counts failures in CLOSED state. After failureThreshold failures, trips to OPEN and rejects all calls instantly. After recoveryTimeout seconds, moves to HALF_OPEN and allows one test call. Success resets to CLOSED.
visibility12 виды
Показ 1-12 из 63 сценарии
Shared Scripts — примеры кода от сообщества — это коллекция практических PHP-сниппетов, которыми делятся разработчики со всего мира. Здесь вы можете:
-
Изучать реальные решения задач: от декодирования GPS и JWT до реализации LRU-кэша, pack/unpack preg_match
-
Сравнивать производительность функций, например,
foreachvsarray_map -
Делиться собственными сниппетами и смотреть, что делают другие
-
Получать вдохновение для своих проектов и быстро находить готовые фрагменты кода
Все примеры открыты и понятны, без внешних зависимостей. Идеально подходит для начинающих и опытных разработчиков, которым нужны рабочие примеры на PHP.
Comments
No comments yet
Be the first to share your thoughts!