Просмотрите и обнаружите сценарии кода, разделяемые сообществом. Найдите примеры, учитесь у других и поделитесь своими собственными фрагментами кода.
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.
129 виды
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.
181 виды
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.
222 виды
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.
83 виды
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.
156 виды
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.
45 виды
Finite State Machine (FSM) in Pure PHP
Анонимный
3 Несколько недель назад
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.
22 виды
PHP 8.5 Property Hooks: Practical Examples
Анонимный
3 Несколько недель назад
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.
11 виды
Minimal Dependency Injection Container
Анонимный
3 Несколько недель назад
A simple DI container with singleton and factory bindings, auto-wiring via reflection, and interface-to-class binding. Under 80 lines, no dependencies.
10 виды
Deep Array Diff: Find All Changes Between Two Arrays
Анонимный
3 Несколько недель назад
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.
11 виды
Parse .env File Without Any Library
Анонимный
3 Несколько недель назад
Read and parse a .env file into an array or into $_ENV / getenv(). Handles comments, quoted values, multiline strings, and variable interpolation.
12 виды
Circuit Breaker Pattern in Pure PHP
Анонимный
3 Несколько недель назад
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.
12 виды
Показ 1-12 из 63 сценарии

Shared Scripts — примеры кода от сообщества — это коллекция практических PHP-сниппетов, которыми делятся разработчики со всего мира. Здесь вы можете:

  • Изучать реальные решения задач: от декодирования GPS и JWT до реализации LRU-кэша, pack/unpack preg_match

  • Сравнивать производительность функций, например, foreach vs array_map

  • Делиться собственными сниппетами и смотреть, что делают другие

  • Получать вдохновение для своих проектов и быстро находить готовые фрагменты кода

Все примеры открыты и понятны, без внешних зависимостей. Идеально подходит для начинающих и опытных разработчиков, которым нужны рабочие примеры на PHP.