(C)oncept-Labs Arrays API

Installs: 26

Dependents: 2

Suggesters: 1

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

pkg:composer/concept-labs/arrays

1.1.1 2025-10-12 09:15 UTC

README

A powerful PHP library for working with arrays using dot notation, recursive operations, and advanced querying capabilities.

License: MIT PHP Version

Overview

The Concept-Labs Arrays library provides a comprehensive suite of tools for manipulating and querying deeply nested PHP arrays. It offers three main components:

  • DotArray: Object-oriented wrapper for array manipulation using dot notation
  • RecursiveDotApi: Static API for recursive array operations with dot notation
  • RecursiveApi: Static API for basic recursive array operations

Features

  • 🎯 Dot Notation Access: Access and manipulate deeply nested arrays using simple dot paths (user.profile.name)
  • 🔄 Recursive Operations: Map, filter, reduce, and transform arrays at any depth
  • 🔍 Advanced Querying: Query arrays with wildcard patterns and column filtering
  • 🛠️ Rich Mutation API: Push, pop, increment, merge, replace, fill and more
  • 📦 Array/Object Access: Use both array syntax ($arr['key']) and object syntax ($arr->key)
  • 🔗 Standard Interfaces: Implements ArrayAccess, IteratorAggregate, JsonSerializable
  • Performant: Optimized for both reference and copy operations

Installation

Install via Composer:

composer require concept-labs/arrays

Requirements

  • PHP 8.0 or higher

For detailed installation instructions, see the Installation Guide.

Quick Start

DotArray - Object-Oriented API

use Concept\Arrays\DotArray\DotArray;

// Create from array
$config = new DotArray([
    'app' => [
        'name' => 'MyApp',
        'version' => '1.0.0',
        'settings' => [
            'debug' => true,
            'timezone' => 'UTC'
        ]
    ]
]);

// Get values using dot notation
echo $config->get('app.name');              // "MyApp"
echo $config->get('app.settings.debug');    // true

// Set values
$config->set('app.settings.locale', 'en');

// Array access syntax
echo $config['app.version'];                // "1.0.0"
$config['app.settings.cache'] = true;

// Object access syntax  
echo $config->app->get('name');             // "MyApp"

// Check existence
if ($config->has('app.settings.debug')) {
    // ...
}

// Remove values
$config->unset('app.settings.debug');

RecursiveDotApi - Static API with Dot Notation

use Concept\Arrays\RecursiveDotApi;

$data = [
    'users' => [
        'admin' => ['name' => 'John', 'role' => 'admin'],
        'guest' => ['name' => 'Jane', 'role' => 'user']
    ]
];

// Get nested value
$name = RecursiveDotApi::get($data, 'users.admin.name'); // "John"

// Set nested value
RecursiveDotApi::set($data, 'users.admin.email', 'john@example.com');

// Check existence
$exists = RecursiveDotApi::has($data, 'users.admin.role'); // true

// Flatten to dot notation
$flat = RecursiveDotApi::flatten($data);
// ['users.admin.name' => 'John', 'users.admin.role' => 'admin', ...]

// Unflatten back to nested
$nested = RecursiveDotApi::unflatten($flat);

RecursiveApi - Basic Recursive Operations

use Concept\Arrays\RecursiveApi;

$data = [
    'products' => [
        ['name' => 'Laptop', 'price' => 999],
        ['name' => 'Mouse', 'price' => 25]
    ]
];

// Map all values
$mapped = RecursiveApi::map($data, fn($value) => 
    is_numeric($value) ? $value * 1.1 : $value
);

// Filter values
$filtered = RecursiveApi::filter($data, fn($value) => 
    !is_numeric($value) || $value > 50
);

// Reduce to single value
$total = RecursiveApi::reduce($data, 
    fn($acc, $val) => is_numeric($val) ? $acc + $val : $acc, 
    0
);

Why Choose Concept-Labs Arrays?

Advantages Over Standard PHP Arrays

  • 🎯 Cleaner Syntax: $data->get('user.profile.name') vs $data['user']['profile']['name'] ?? null
  • 🛡️ Safe Access: No more isset() checks or null coalescing operators
  • 🚀 Auto-path Creation: Automatically creates intermediate arrays when setting values
  • 🔧 Rich API: 100+ methods vs manual implementations
  • 🔍 Advanced Queries: Wildcard patterns and SQL-like WHERE clauses
  • ⚡ Performance: Static API (RecursiveDotApi) has minimal overhead (~5% slower than native)

Advantages Over Other Libraries

Feature Standard Arrays Laravel Collections dflydev/dot Concept-Labs
Dot Notation
Wildcard Queries
Functional Ops ⚠️ Native only
Path Operations ⚠️ Limited ✅ Full
Framework Agnostic
Static + OOP API ⚠️ Native

See full comparison →

Key Concepts

Dot Notation

Access nested array elements using dot-separated paths:

$array = [
    'database' => [
        'connections' => [
            'mysql' => [
                'host' => 'localhost'
            ]
        ]
    ]
];

// Instead of: $array['database']['connections']['mysql']['host']
// Use: $dotArray->get('database.connections.mysql.host')

Mutable vs Immutable Operations

$data = new DotArray(['count' => 5]);

// Get returns a reference (mutable)
$ref = &$data->get('count');
$ref = 10; // Original data is modified

// Child with copy (immutable)
$child = $data->child('count', true);
$child->set('value', 20); // Original data unchanged

// Child with reference (mutable)
$child = $data->child('count', false);
$child->set('value', 20); // Original data is modified

Documentation

Getting Started

Core Documentation

Reference

Common Use Cases

Configuration Management

$config = new DotArray($defaultConfig);
$config->merge($userConfig);
$config->fill($requiredDefaults);

Data Transformation

$data->walk(function(&$value, $path) {
    if (is_string($value)) {
        $value = trim($value);
    }
});

Filtering & Querying

// Filter nested data
$adults = $users->filter(fn($u) => $u['age'] >= 18, 0, 'users');

// Query with wildcards (DotQuery)
$result = $query->select('users.*.name');

Array Manipulation

// Stack operations
$config->push('logs.entries', $newEntry);
$lastEntry = $config->pop('logs.entries');

// Numeric operations
$config->increment('stats.visits');
$config->decrement('stats.credits', 10);

// Boolean operations
$config->toggle('features.darkMode');

Advanced Features

Only/Except

Extract or exclude specific paths:

$subset = $data->only(['user.name', 'user.email']);
$without = $data->except(['user.password', 'user.token']);

Merge Strategies

// Combine arrays
$data->merge($newData);

// Replace values
$data->replace($newData);

// Fill missing keys only
$data->fill($defaults);

Flatten/Unflatten

$flat = $data->flatten(); // Convert to dot notation
$nested = $data->unflatten($flat); // Convert back to nested

Testing

Run the test suite:

composer test

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This library is licensed under the MIT License - see the LICENSE file for details.

Credits

Developed by Concept Labs

Author: Viktor Halytskyi concept.galitsky@gmail.com

Support

Related Projects