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 small PHP helper library for working with arrays. It provides safe, convenient methods to get and set values (including nested paths), filter and merge data, and simplify common array operations in Yii and any PHP project.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Update to the latest version via Composer:
   ```bash
   composer require yiisoft/arrays:^3.2.1

No additional configuration is required—it remains a standalone helper with backward compatibility.

  1. 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
    
  2. Key Methods to Explore (Updated)

    • 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.
    • New/Improved: htmlEncode(): Now optimized for performance (backed by yiisoft/strings 2.6) and includes built-in benchmarking. Supports PHP 8.5’s stricter type handling.
    • group(): Enhanced with stricter PSalm types (useful for static analysis) and improved type inference. Now fully compatible with PHP 8.5’s type system.
    • New: Full PHP 8.5 support, including compatibility with modern array features (e.g., spread operator, array_unpack). The package now leverages PHP 8.5’s stricter type checks and new array functions.

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. HTML Encoding for API Responses (Optimized) Use the benchmarked and optimized htmlEncode() for sanitizing user-generated content in responses:

    $userComments = ['comment' => '<script>alert("XSS")</script>'];
    $safeComments = ArrayHelper::htmlEncode($userComments);
    // Returns: ['comment' => '&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;']
    

    Benchmarking: The method now includes built-in performance benchmarks and is optimized for large datasets (backed by yiisoft/strings 2.6). Test with:

    $start = microtime(true);
    $encoded = ArrayHelper::htmlEncode($largeArray);
    $time = microtime(true) - $start;
    echo "Encoding took {$time}s";
    
  5. Grouping Data with Strict Typing (Enhanced) Leverage group() with improved PSalm support for better IDE autocompletion and static analysis:

    $users = [
        ['name' => 'John', 'role' => 'admin'],
        ['name' => 'Jane', 'role' => 'user'],
    ];
    $grouped = ArrayHelper::group($users, fn($user) => $user['role']);
    // PSalm now enforces stricter return types for grouped arrays, reducing runtime errors.
    // Example: PSalm will flag if 'role' might be missing or not a string/key-compatible type.
    
  6. PHP 8.5 Integration (New) Use the helper with PHP 8.5’s new array features, including spread operator and array_unpack:

    $array = ['a' => 1, 'b' => 2];
    $merged = ArrayHelper::merge($array, ['...$array']); // PHP 8.5 spread operator
    $unpacked = ArrayHelper::map($array, fn($val) => [$val, ...$val]); // PHP 8.5 array unpacking
    
  7. Selective HTML Encoding (New Pattern) Combine htmlEncode() with map() for selective encoding, leveraging optimized performance:

    $data = ['title' => 'Safe', 'content' => '<b>Risky</b>'];
    $encoded = ArrayHelper::map($data, fn($val, $key) =>
        $key === 'content' ? ArrayHelper::htmlEncode($val) : $val
    );
    

Integration Tips

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

    $this->app->singleton('arrayHelper', fn() => new ArrayHelper());
    
  • API Response Sanitization (Optimized) Combine htmlEncode() with toArray() for safe JSON responses, leveraging the optimized performance:

    $response = ArrayHelper::toArray($model->toArray());
    $sanitized = ArrayHelper::htmlEncode($response);
    return response()->json($sanitized);
    
  • PHP 8.5 Support (New) Leverage PHP 8.5 features (e.g., array_unpack, spread operator) in callbacks:

    $array = ['a' => 1, 'b' => 2];
    $transformed = ArrayHelper::map($array, fn($val) => [$val, ...[$val]]); // PHP 8.5 unpacking
    
  • PSalm Static Analysis (Enhanced) Use group() with PSalm to catch type-related issues early:

    $grouped = ArrayHelper::group($users, fn($user) => $user['role']);
    // PSalm will enforce that 'role' is a string or compatible type.
    

Gotchas and Tips

Pitfalls

  1. Path Syntax in getValue/setValue

    • Invalid paths return null (not [] or exceptions).
    • Example: getValue(['a' => 1], 'a.b')null.
  2. Deep Merge Overwrites

    • 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).
  4. htmlEncode() Performance Caveats (Updated)

    • While optimized, avoid encoding already-safe data (e.g., static configs).
    • Benchmark for large arrays—overuse may still impact performance in edge cases.
    • Note: The method now uses yiisoft/strings 2.6, which may handle non-string values differently (e.g., null, objects). Test thoroughly with mixed-type arrays.
  5. PHP 8.5 Deprecations (New)

    • Ensure compatibility with PHP 8.5’s stricter type checks (e.g., array_unpack behavior in callbacks).
    • Avoid deprecated functions (e.g., create_function) if used in legacy code with the helper.
    • Example: PHP 8.5 may throw warnings for loose type comparisons in callbacks.
  6. PSalm Type Mismatches (Enhanced)

    • group() now enforces stricter types. Ensure grouped keys are compatible with PSalm’s expectations:
      $grouped = ArrayHelper::group($users, fn($user) => $user['role']);
      // PSalm will flag if 'role' might be missing or not a string/key-compatible type.
      
  7. PHP 8.5 Array Function Changes (New)

    • Be cautious with array_unpack in callbacks—PHP 8.5 may enforce stricter rules for unpacked values.
    • Example: Unpacking non-array values may now trigger warnings.

Debugging Tips

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

  • Inspect Grouped Arrays (Enhanced) With PSalm’s stricter types, verify grouped keys at compile time:

    $grouped = ArrayHelper::group($users, fn($user) => $user['role']);
    // PSalm will flag if 'role' might be missing or not a string.
    
  • PHP 8.5 Deprecations Test for deprecated functions (e.g., create_function) if using legacy code with the helper.

  • Benchmark htmlEncode() (New)

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor