https://github.com/vasiliy-makogon/php-collection
CoverArray (aka PHP Collection) - library for convenient and flexible work with arrays in object-oriented representation.
https://github.com/vasiliy-makogon/php-collection
array-object array-wrapper arrayobject collection cover-array php-array php-array-collection php-array-cover php-array-object php-array-wrapper php-collection
Last synced: 3 months ago
JSON representation
CoverArray (aka PHP Collection) - library for convenient and flexible work with arrays in object-oriented representation.
- Host: GitHub
- URL: https://github.com/vasiliy-makogon/php-collection
- Owner: Vasiliy-Makogon
- Created: 2018-10-24T14:19:30.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2025-02-18T02:25:28.000Z (over 1 year ago)
- Last Synced: 2025-04-22T12:36:17.694Z (about 1 year ago)
- Topics: array-object, array-wrapper, arrayobject, collection, cover-array, php-array, php-array-collection, php-array-cover, php-array-object, php-array-wrapper, php-collection
- Language: PHP
- Homepage:
- Size: 154 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README

**Other languages:**
- [Русская документация](docs/README_ru.md)
- [Documentation française](docs/README_fr.md)
- [Deutsche Dokumentation](docs/README_de.md)
- [Documentazione italiana](docs/README_it.md)
- [日本語ドキュメント](docs/README_jp.md)
- [Documentación en español](docs/README_es.md)
- [한국어 문서](docs/README_kr.md)
- [简体中文文档](docs/README_cn.md)
- [繁體中文文件](docs/README_tw.md)
- [Dokumentasi Bahasa Indonesia](docs/README_id.md)
- [Documentação em Português (BR)](docs/README_br.md)
- [हिंदी दस्तावेज़](docs/README_hi.md)
- [التوثيق بالعربية](docs/README_ar.md)
- [Türkçe Dokümantasyon](docs/README_tr.md)
- [Tài liệu tiếng Việt](docs/README_vi.md)
---
## State
### Test Status
| PHP Version | Status |
|-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 8.0 | [](https://github.com/Vasiliy-Makogon/PHP-Collection/actions/workflows/php80.yml) |
| 8.1 | [](https://github.com/Vasiliy-Makogon/PHP-Collection/actions/workflows/php81.yml) |
| 8.2 | [](https://github.com/Vasiliy-Makogon/PHP-Collection/actions/workflows/php82.yml) |
| 8.3 | [](https://github.com/Vasiliy-Makogon/PHP-Collection/actions/workflows/php83.yml) |
| 8.4 | [](https://github.com/Vasiliy-Makogon/PHP-Collection/actions/workflows/php84.yml) |
| 8.5 | [](https://github.com/Vasiliy-Makogon/PHP-Collection/actions/workflows/php85.yml) |
### Code Coverage
[](https://codecov.io/gh/Vasiliy-Makogon/PHP-Collection)
## Requirements
PHP >= 8.0
## Installation
```
composer require krugozor/cover
```
# CoverArray: Object-Oriented Array Wrapper for PHP (PHP Collection)
Created by human, verified and tested by artificial intelligence. Release 2026
## Why CoverArray Was Created
In modern PHP development, we often work with arrays as the primary data structure. However, PHP's native array functions have several limitations that CoverArray solves.
### The Problem with Native PHP Arrays
- **Inconsistent function naming**: Some functions use underscores (`array_map`), others don't (`usort`)
- **Mixed parameter orders**: Functions like `array_map($callback, $array)` vs `array_filter($array, $callback)`
- **No method chaining**: Native functions return new arrays, requiring intermediate variables
- **Limited type safety**: No IDE autocompletion or static analysis support
- **Verbose syntax**: Complex operations require nested function calls
### What CoverArray Solves
CoverArray provides a clean, object-oriented interface that wraps PHP arrays while maintaining full compatibility with native functions:
```php
// Data: users with age and status
// Task: get names of active users over 18, sorted by descending score
$users = [
['name' => 'Alice', 'age' => 25, 'active' => true, 'score' => 85],
['name' => 'Bob', 'age' => 17, 'active' => false, 'score' => 45],
['name' => 'Charlie', 'age' => 32, 'active' => true, 'score' => 92],
['name' => 'Diana', 'age' => 19, 'active' => true, 'score' => 78],
['name' => 'Eve', 'age' => 22, 'active' => false, 'score' => 61],
];
```
#### Before (Native PHP):
```php
$filtered = array_filter($users, fn($u) => $u['active'] && $u['age'] >= 18);
$sorted = usort($filtered, fn($a, $b) => $b['score'] <=> $a['score']) ? $filtered : [];
$names = array_column($sorted, 'name');
$result = implode(', ', $names); // Charlie, Alice, Diana
```
#### After (CoverArray):
```php
// EVERYTHING IN ONE LINE!
$result = CoverArray::fromArray($users)
->filter(fn($u) => $u->active && $u->age >= 18)
->usort(fn($a, $b) => $b->score <=> $a->score)
->values()
->column('name')
->implode(', '); // Charlie, Alice, Diana
```
### Key Benefits
* **No External Dependencies:** Pure PHP implementation, no additional packages required
* **Consistent API:** All methods follow `$array->method($arguments)` pattern
* **Method Chaining:** Chain multiple operations in a readable way
* **IDE Support:** Full autocompletion and type hints
* **Modern Syntax:** Designed for PHP 8.0+ with strict typing
* **Dot Notation:** Easy nested data access with `$array->get('user.profile.name')`
* **JSON Support:** Built-in serialization/deserialization
* **Immutable Operations:** Most methods return new instances, preserving original data
* **Full Compatibility:** Works seamlessly with existing array-based code
### Real-World Use Cases
#### Example 1: Configuration Management with Dot Notation
```php
// Load and access nested configuration safely
$config = CoverArray::fromJson(file_get_contents('config.json'));
// Direct nested access with default fallbacks
$dbHost = $config->get('database.connections.mysql.host', fn($value) => $value ?? 'localhost');
$dbPort = $config->get('database.connections.mysql.port', fn($value) => $value ?? 3306);
// Access with callback for complex defaults
$apiKeys = $config->get('services.payment.keys', function($keys) {
return $keys ?? CoverArray::fromArray([
'public' => 'default_public_key',
'secret' => 'default_secret_key'
]);
});
```
#### Example 2: API Response Processing Pipeline
```php
// Real-world API processing: filter, transform, and extract data
$apiResponse = CoverArray::fromJson($httpResponse)
->get('data.users', function (mixed $users): CoverArray {
if ($users === null) {
return new CoverArray();
}
/** @var CoverArray $users */
return $users
->filter(fn($u) => $u['active'] == '1' && $u['email_verified'])
->map(fn($u) => [
'id' => $u['id'],
'name' => $u['first_name'] . ' ' . $u['last_name'],
'email' => strtolower($u['email']),
'role' => $u['role'] ?? 'user'
])
->usort(fn($a, $b) => $a['name'] <=> $b['name']);
});
// Extract specific columns for dropdown
$userOptions = $apiResponse->column('name', 'id')->getDataAsArray();
```
#### Example 3: Log Analysis and Error Reporting
```php
// Parse application logs and extract error patterns
$logLines = CoverArray::fromExplode("\n", file_get_contents('app.log'))
->filter(fn($line) => !empty(trim($line)));
// Extract and categorize errors
$errors = $logLines
->filter(fn($line) => str_contains($line, 'ERROR'))
->map(function($line) {
preg_match('/\[(.*?)\].*ERROR:\s*(\w+)\s*-\s*(.*)/', $line, $matches);
return [
'timestamp' => $matches[1] ?? 'Unknown',
'type' => $matches[2] ?? 'General',
'message' => $matches[3] ?? $line
];
});
// Group by error type and count occurrences
$errorStats = $errors
->column('type')
->countValues()
->arsort(); // Sort by frequency
// Generate error report
$report = "Error Report:\n";
foreach ($errorStats as $type => $count) {
$report .= "- {$type}: {$count} occurrences\n";
}
// Find most recent critical error
$lastCritical = $errors
->filter(fn($e) => $e['type'] === 'Critical')
->last();
```
CoverArray bridges the gap between PHP's powerful array functions and modern object-oriented practices, making array manipulation more expressive, maintainable, and enjoyable.
## Comparison Table: CoverArray Methods vs PHP Array Functions
#PHP FunctionCoverArray MethodStatusNotes1array_allall()✅Implemented with polyfill for older PHP versions2array_anyany()✅Implemented with polyfill for older PHP versions3array_change_key_casechangeKeyCase()✅Full implementation4array_chunkchunk()✅Full implementation5array_columncolumn()✅Full implementation6array_combinecombine()✅Full implementation (static method)7array_count_valuescountValues()✅Full implementation8array_diffdiff()✅Full implementation9array_diff_assocdiffAssoc()✅Full implementation10array_diff_keydiffKey()✅Full implementation11array_diff_uassocdiffUassoc()✅Full implementation12array_diff_ukeydiffUkey()✅Full implementation13array_fillfill()✅Full implementation (static method)14array_fill_keysfillKeys()✅Full implementation (static method)15array_filterfilter()✅Full implementation16array_findfind()✅Implemented with polyfill for older PHP versions17array_find_keyfindKey()✅Implemented with polyfill for older PHP versions18array_firstfirst()✅Implemented with polyfill for older PHP versions19array_flipflip()✅Full implementation20array_intersectintersect()✅Full implementation21array_intersect_associntersectAssoc()✅Full implementation22array_intersect_keyintersectKey()✅Full implementation23array_intersect_uassocintersectUassoc()✅Full implementation24array_intersect_ukeyintersectUkey()✅Full implementation25array_is_listisList()✅Implemented with polyfill for older PHP versions26array_key_existskeyExists()✅Full implementation27array_key_firstkeyFirst()✅Uses built-in function28array_key_lastkeyLast()✅Uses built-in function29array_keyskeys()✅Full implementation30array_lastlast()✅Implemented with polyfill for older PHP versions31array_mapmap()✅Full implementation32array_mergemerge()✅Full implementation33array_merge_recursivemergeRecursive()✅Full implementation34array_multisortmultisort()✅Full implementation (mutating)35array_padpad()✅Full implementation36array_poppop()✅Full implementation (mutating)37array_productproduct()✅Full implementation38array_pushpush() / append()✅Full implementation (mutating)39array_randrand()✅Full implementation40array_reducereduce()✅Full implementation41array_replacereplace()✅Full implementation42array_replace_recursivereplaceRecursive()✅Full implementation43array_reversereverse()✅Full implementation44array_searchsearch()✅Full implementation45array_shiftshift()✅Full implementation (mutating)46array_sliceslice()✅Full implementation47array_splicesplice()✅Full implementation (mutating)48array_sumsum()✅Full implementation49array_udiffudiff()✅Full implementation50array_udiff_assocudiffAssoc()✅Full implementation51array_udiff_uassocudiffUassoc()✅Full implementation52array_uintersectuintersect()✅Full implementation53array_uintersect_assocuintersectAssoc()✅Full implementation54array_uintersect_uassocuintersectUassoc()✅Full implementation55array_uniqueunique()✅Full implementation56array_unshiftunshift() / prepend()✅Full implementation (mutating)57array_valuesvalues()✅Full implementation58array_walkwalk()✅Full implementation (mutating)59array_walk_recursivewalkRecursive()✅Full implementation (mutating)60arsortarsort()✅Full implementation (mutating)61asortasort()✅Full implementation (mutating)62compactcompact()⚠️Not implementable (PHP scope limitations). Use: CoverArray::fromArray(compact(...))63countcount()✅Implementation of Countable interface64currentcurrent()✅Full implementation65endend()✅Full implementation (mutating)66extractextract()✅Full implementation67in_arrayin()✅Full implementation68keykey()✅Full implementation69key_existskeyExists()✅Full implementation (same as array_key_exists)70krsortkrsort()✅Full implementation (mutating)71ksortksort()✅Full implementation (mutating)72listlist()⚠️Not implementable (language construct). Use: list($a, $b) = $cover->getDataAsArray()73natcasesortnatcasesort()✅Full implementation (mutating)74natsortnatsort()✅Full implementation (mutating)75nextnext()✅Full implementation (mutating)76pospos()✅Alias of current()77prevprev()✅Full implementation (mutating)78rangerange()✅Full implementation (static method)79resetreset()✅Full implementation (mutating)80rsortrsort()✅Full implementation (mutating)81shuffleshuffle()✅Full implementation (mutating)82sortsort()✅Full implementation (mutating)83uasortuasort()✅Full implementation (mutating)84uksortuksort()✅Full implementation (mutating)85usortusort()✅Full implementation (mutating)
### Additional CoverArray Methods
MethodPurposeAccess__clone()Creates a shallow copy with deep cloning of immediate object propertiesMagic__get()Gets a property value using object property syntaxMagic__isset()Checks if a property is setMagic__serialize()Serializes the object for serializationMagic__set()Sets a property value using object property syntaxMagic__toString()Returns a string representation of the objectMagic__unserialize()Unserializes the object from serialized dataMagic__unset()Unsets a propertyMagicclear()Clears all dataPubliccopy()Creates and returns a copy of the current object instancePubliceach()Applies a callback to each element and returns a new instance with preserved keys (immutable, non-recursive)PubliceachRecursive()Recursively applies a callback to each element and returns a new instance (immutable, recursive)PublicfromArray()Creates a CoverArray from a native PHP arrayPublic StaticfromExplode()Creates a CoverArray from a string using explode()Public StaticfromJson()Creates a CoverArray instance from a JSON stringPublic Staticget()Returns data by keys of the current object using dot notationPublicgetData()Returns the internal data array as-is without any conversionPublicgetDataAsArray()Returns the current object's data as a native PHP arrayPublicgetIterator()Returns an iterator for the array (IteratorAggregate interface)Publicimplode()Joins array elements with a stringPublicisEmpty()Checks if the array is emptyPublicitem()Returns the collection element with the given index as the resultPublicjsonSerialize()Specifies data which should be serialized to JSON (JsonSerializable interface)PublicoffsetExists()Checks whether the specified offset exists in the array (ArrayAccess interface)PublicoffsetGet()Returns the value at the specified offset (ArrayAccess interface)PublicoffsetSet()Sets the value at the specified offset (ArrayAccess interface)PublicoffsetUnset()Unsets the value at the specified offset (ArrayAccess interface)PublicsetData()Sets the internal data for the CoverArrayPublictoJson()Converts the CoverArray to a JSON stringPublic