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.
## 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.
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
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.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.array_unpack). The package now leverages PHP 8.5’s stricter type checks and new array functions.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'
Form Request Validation Flatten or sanitize request data:
$requestData = ArrayHelper::toArray($request->all());
$filtered = ArrayHelper::filter($requestData, fn($val) => !empty($val));
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);
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' => '<script>alert("XSS")</script>']
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";
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.
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
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
);
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.
Path Syntax in getValue/setValue
null (not [] or exceptions).getValue(['a' => 1], 'a.b') → null.Deep Merge Overwrites
merge(['a' => 1], ['a' => 2]) → ['a' => 2].Callback Context in filter/map
htmlEncode() Performance Caveats (Updated)
yiisoft/strings 2.6, which may handle non-string values differently (e.g., null, objects). Test thoroughly with mixed-type arrays.PHP 8.5 Deprecations (New)
array_unpack behavior in callbacks).create_function) if used in legacy code with the helper.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.
PHP 8.5 Array Function Changes (New)
array_unpack in callbacks—PHP 8.5 may enforce stricter rules for unpacked values.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)
How can I help you explore Laravel packages today?