Introducing Slash: A Minimal, Elegant Utility Library for PHP
PHP has grown to be a versatile and powerful language for web development. But sometimes, working with arrays and collections can get repetitive, verbose, or just plain tedious. That’s where Slash comes in — a lightweight, expressive utility library that makes array and data manipulation effortless and elegant.
Whether you're building a Laravel app or writing raw PHP, Slash helps you get more done with less code.
Why Slash?
Think of Slash as PHP's answer to Lodash in JavaScript or Collections in Laravel — but simplified and framework-agnostic. It gives you expressive, chainable utilities without any heavy dependencies.
With slash(), you can do things like grouping, mapping, flattening, finding the max, or getting the last elements — all in one clean line of code.
Let’s dive into some real examples.
Getting Started
Assuming you’ve already installed the Slash library (or autoloaded it via Composer), you can start using it like this:
slash()->map([1, 2, 3], fn($n) => $n * 2); // => [2, 4, 6]
The slash() function returns a utility object packed with helper methods.
groupBy
Let’s say you have a list of records with repeated IDs and you want to group them by id. Normally, that would require a foreach loop. But with Slash:
$records = [ [ "id" => 1, "value1" => 5, "value2" => 10 ], [ "id" => 1, "value1" => 1, "value2" => 2 ], [ "id" => 2, "value1" => 50, "value2" => 100 ], [ "id" => 2, "value1" => 15, "value2" => 20 ], [ "id" => 3, "value1" => 15, "value2" => 20 ] ]; $grouped = slash()->groupBy($records, 'id'); /* * Result: * [ * 1 => [ [...], [...] ], * 2 => [ [...], [...] ], * 3 => [ [...] ] * ] */
Easy, clean, and readable.
map
Need to transform an array? Use map:
slash()->map([1, 2, 3], fn ($n) => $n * 2); // => [2, 4, 6]
This works exactly like JavaScript’s Array.prototype.map.
max
Quickly find the largest value in a dataset:
slash()->max([1, 2, 3]); // => 3
🪆 flatten
Working with nested arrays? flatten() handles any depth:
slash()->flatten([1, [2, [3]]]); // => [1, 2, 3]
No more array_merge gymnastics.
last
Get the last n elements from an array:
slash()->last([1, 2, 3], 2); // => [2, 3]
If you just want the final item:
slash()->last([1, 2, 3]); // => 3
Conclusion
If you're tired of writing verbose code for simple operations, Slash is your new best friend. It’s compact, expressive, and gets out of your way — letting you write clean, readable PHP with modern flair.
Whether you're building a small utility script or a full-featured app, Slash can help you move faster and code cleaner.
📦 What’s Next?
We’re just scratching the surface. Future features could include:
- filter
- sum
- pluck
- sortBy
- Chaining support (slash()->collection($array)->map(...)->filter(...))
Your feedback helps — what would you like to see in the next version of Slash?
Please login to leave a comment.