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

Array Functions Laravel Package

spatie/array-functions

Handy PHP array utilities from Spatie. Adds small, focused functions in the Spatie namespace (e.g., array_rand_value to pick a random value) to complement built-in array helpers. Install via Composer and use directly in your code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

composer require spatie/array-functions

No configuration required—functions are globally available via the array_functions facade or direct use.

First Use Case: Quick Array Manipulation

Replace Laravel’s built-in array_pluck() with a more flexible alternative:

use Spatie\ArrayFunctions\ArrayFunctions;

$data = [
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
];

// Extract 'name' values (like array_column)
$names = ArrayFunctions::pluck($data, 'name');
// ['John', 'Jane']

// Group by 'id' (like array_column but with keys)
$grouped = ArrayFunctions::groupBy($data, 'id');
// [1 => ['name' => 'John'], 2 => ['name' => 'Jane']]

Where to Look First

  • Facade: Spatie\ArrayFunctions\ArrayFunctions (or array_functions() helper).
  • Documentation: GitHub README for full function list.
  • Tests: /tests for usage examples and edge cases.

Implementation Patterns

Common Workflows

  1. Data Transformation Use map() to modify array values in-place:

    $prices = [10, 20, 30];
    $discounted = ArrayFunctions::map($prices, fn($price) => $price * 0.9);
    // [9, 18, 27]
    
  2. Nested Array Handling Access deep keys with get():

    $user = ['profile' => ['name' => 'Alice']];
    $name = ArrayFunctions::get($user, 'profile.name'); // 'Alice'
    
  3. Conditional Filtering Filter arrays with where():

    $users = [
        ['active' => true, 'name' => 'Bob'],
        ['active' => false, 'name' => 'Charlie'],
    ];
    $activeUsers = ArrayFunctions::where($users, 'active', true);
    // [['active' => true, 'name' => 'Bob']]
    
  4. Laravel Integration Replace Eloquent collections with array functions for lightweight operations:

    $ids = ArrayFunctions::pluck($models->toArray(), 'id');
    

Integration Tips

  • Combine with Laravel Collections: Use array_functions() for preprocessing before converting to a collection:
    $filtered = ArrayFunctions::where($rawData, 'status', 'active');
    $collection = collect($filtered);
    
  • Custom Logic: Extend with tap() for side effects:
    ArrayFunctions::tap($data, fn($arr) => $this->logArray($arr));
    
  • Performance: Prefer array_functions() over native PHP for complex operations (e.g., where with multiple conditions).

Gotchas and Tips

Pitfalls

  1. Immutable Operations Most functions return new arrays; avoid assuming in-place modification:

    $original = ['a' => 1];
    ArrayFunctions::set($original, 'b', 2); // $original remains unchanged
    
  2. Key Collisions in merge() Overlapping keys in ArrayFunctions::merge() will overwrite values (like native array_merge):

    ArrayFunctions::merge(['a' => 1], ['a' => 2]); // ['a' => 2]
    
  3. Nested get() Failures Silent failures on missing nested keys:

    ArrayFunctions::get(['a' => ['b' => null]], 'a.b.c'); // null (not an error)
    

    Use ArrayFunctions::has() to check existence first.

  4. Callback Context map()/filter() callbacks lose array context. Use fn($value, $key) => ... for key access.

Debugging Tips

  • Validate Inputs: Use ArrayFunctions::isAssoc() or ArrayFunctions::isList() to debug structure.
  • Default Values: Chain with ArrayFunctions::get() defaults:
    $value = ArrayFunctions::get($array, 'key', 'default');
    
  • Logging: Use ArrayFunctions::dump() for visual debugging (similar to dd() but for arrays).

Extension Points

  1. Custom Helpers Create a trait to wrap frequently used combinations:

    trait ArrayHelper {
        public function filterActive(array $items): array {
            return ArrayFunctions::where($items, 'active', true);
        }
    }
    
  2. Override Defaults Extend the ArrayFunctions class to modify behavior (e.g., strict mode for get()):

    class StrictArrayFunctions extends ArrayFunctions {
        public static function get(array $array, string $key, $default = null): mixed {
            if (!array_key_exists($key, $array)) {
                throw new \InvalidArgumentException("Key '$key' not found");
            }
            return parent::get($array, $key, $default);
        }
    }
    
  3. Performance Tuning For large arrays, prefer native PHP functions (e.g., array_map) over ArrayFunctions for micro-optimizations, but benchmark first.

Config Quirks

  • No Configuration: All functions are stateless; no config/array-functions.php exists.
  • Facade Binding: Ensure the facade is bound in AppServiceProvider if using custom extensions:
    $this->app->bind('array_functions', fn() => new StrictArrayFunctions());
    
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