Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Arrays Laravel Package

yiisoft/arrays

yiisoft/arrays is a lightweight PHP utility library for working with arrays: fetch values by key/path, set and remove nested items, merge and filter data, and perform common transformations. Designed for Yii projects but usable standalone.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require yiisoft/arrays
    

    No additional configuration is required—it’s a standalone helper.

  2. First Use Case Import the helper and use it for basic array operations:

    use Yiisoft\Arrays\ArrayHelper;
    
    $array = ['a' => 1, 'b' => 2, 'c' => 3];
    $value = ArrayHelper::getValue($array, 'b'); // Returns 2
    
  3. Key Methods to Explore

    • getValue(): Retrieve nested array values (e.g., getValue($array, 'user.name')).
    • setValue(): Set nested array values.
    • merge(): Deep merge arrays.
    • filter(): Filter arrays by callback.
    • map(): Transform arrays with a callback.

Implementation Patterns

Common Workflows

  1. Nested Data Handling Use getValue()/setValue() for Eloquent models or API responses:

    $user = ['user' => ['name' => 'John', 'address' => ['city' => 'NY']]];
    $city = ArrayHelper::getValue($user, 'user.address.city'); // 'NY'
    
  2. Form Request Validation Flatten or sanitize request data:

    $requestData = ArrayHelper::toArray($request->all());
    $filtered = ArrayHelper::filter($requestData, fn($val) => !empty($val));
    
  3. Configuration Merging Deep merge configs (e.g., environment-specific overrides):

    $baseConfig = require 'config/base.php';
    $envConfig = require 'config/env.php';
    $merged = ArrayHelper::merge($baseConfig, $envConfig);
    
  4. Collection-Like Operations Replace collect() for simple array transformations:

    $prices = [100, 200, 300];
    $discounted = ArrayHelper::map($prices, fn($price) => $price * 0.9);
    

Integration Tips

  • Laravel Service Providers Bind the helper as a singleton for global access:

    $this->app->singleton('arrayHelper', fn() => new ArrayHelper());
    

    Then inject via constructor or resolve with app('arrayHelper').

  • Form Requests Use ArrayHelper::getValue($request->all(), 'user.id') to safely access nested form fields.

  • API Responses Normalize responses before JSON encoding:

    $response = ArrayHelper::toArray($model->toArray());
    

Gotchas and Tips

Pitfalls

  1. Path Syntax in getValue/setValue

    • Uses dot notation (user.address.city), but invalid paths return null (not [] or exceptions).
    • Example: getValue(['a' => 1], 'a.b')null.
  2. Deep Merge Overwrites

    • ArrayHelper::merge() recursively merges, but later keys overwrite earlier ones for duplicate paths.
    • Example:
      merge(['a' => 1], ['a' => 2]) // ['a' => 2]
      
  3. Callback Context in filter/map

    • Callbacks receive value + key (not array reference), so avoid side effects:
      // ❌ Avoid (modifies original array)
      ArrayHelper::map($array, fn(&$val) => $val++);
      

Debugging Tips

  • Validate Paths Use ArrayHelper::getValue($array, 'path', null) to test paths before relying on them.

  • Inspect Merged Arrays For complex merges, log intermediate steps:

    $step1 = ArrayHelper::merge($a, $b);
    $step2 = ArrayHelper::merge($step1, $c);
    

Extension Points

  1. Custom Callbacks Extend filter()/map() with reusable callbacks:

    $isActive = fn($val) => $val === 'active';
    ArrayHelper::filter($statuses, $isActive);
    
  2. Path Manipulation Combine with Str::of() for dynamic paths:

    use Yiisoft\Arrays\ArrayHelper;
    use Illuminate\Support\Str;
    
    $path = Str::of('user')->append('.address')->toString();
    ArrayHelper::getValue($data, $path);
    
  3. Integration with Laravel Collections Use ArrayHelper for preprocessing before converting to collections:

    $cleaned = ArrayHelper::filter($rawData, fn($v) => $v !== null);
    collect($cleaned)->pluck('id');
    

Performance Notes

  • Avoid Overuse in Loops getValue()/setValue() are not optimized for bulk operations—use native PHP or array_walk for loops.

  • Memory Efficiency For large arrays, prefer ArrayHelper::filter() over array_filter() with closures if the helper’s implementation is more memory-efficient (benchmark first).

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport