Moving between JavaScript and PHP is fun... until you touch arrays.
In JavaScript, chaining array methods feels natural:
arr.map().filter().reduce()
In PHP?
You can do similar things, but it often feels fragmented, noisy, or
less expressive.
That's why I built JsArray --- a small PHP library inspired by
JavaScript arrays, focused on readability, predictability, and
developer happiness.
What is JsArray?
JsArray is a lightweight wrapper around native PHP arrays that gives
you familiar methods like:
-
map -
filter -
reduce -
forEach -
find -
every -
some
All chainable. All explicit. All pure PHP.
$result = JsArray::from([1, 2, 3, 4])
->map(fn($n) => $n * 2)
->filter(fn($n) => $n > 4)
->toArray();
// [6, 8]
No magic. No macros. Just clean, readable code.
Immutable by Default (Safe Mode 🛡️)
By default, JsArray is immutable.
That means every operation returns a new instance, and the original
array stays untouched.
$original = JsArray::from([1, 2, 3]);
$doubled = $original->map(fn($n) => $n * 2);
$original->toArray(); // [1, 2, 3]
$doubled->toArray(); // [2, 4, 6]
Why this matters
- No accidental side effects
- Easier debugging
- More predictable behavior
- Very familiar if you come from JavaScript or FP-style code
Mutable Mode (When You Want Performance ⚡)
Sometimes, you do want to mutate the array directly --- especially in
performance-critical paths.
In mutable mode, methods modify the same instance instead of
creating new ones.
$array = JsArray::from([1, 2, 3])->mutable();
$array->map(fn($n) => $n * 2);
$array->filter(fn($n) => $n > 2);
$array->toArray(); // [4, 6]
Final Thoughts
If you:
- write PHP daily
- enjoy JavaScript-style APIs
- care about readable, maintainable code
Then JsArray might feel right at home.
I’m still iterating on it, so feedback, ideas, and criticism are very welcome 🙌
DX matters — we stare at this code all day anyway.
Top comments (0)