PHPackages                             jsarray/jsarray - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. jsarray/jsarray

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jsarray/jsarray
===============

JavaScript-accurate Array wrapper for PHP with immutable operations

v2.1.0(3mo ago)642MITPHPPHP ^8.0

Since Feb 2Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/omer73364/JsArray)[ Packagist](https://packagist.org/packages/jsarray/jsarray)[ Docs](https://github.com/omer73364/jsarray)[ RSS](/packages/jsarray-jsarray/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (5)Used By (0)

JsArray - JavaScript Arrays in PHP
==================================

[](#jsarray---javascript-arrays-in-php)

[![Packagist Version](https://camo.githubusercontent.com/72f0d40c4cfd4b185ed4efdf97d5333acf11581a058c99970b5d5438908544f6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a7361727261792f6a736172726179)](https://camo.githubusercontent.com/72f0d40c4cfd4b185ed4efdf97d5333acf11581a058c99970b5d5438908544f6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a7361727261792f6a736172726179)[![PHP Version](https://camo.githubusercontent.com/b2bd49e3bcdb988b3d1aa2f98f7bc6f34a5fd2db27e555fbfbc8ac846dae568f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6a7361727261792f6a736172726179)](https://camo.githubusercontent.com/b2bd49e3bcdb988b3d1aa2f98f7bc6f34a5fd2db27e555fbfbc8ac846dae568f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6a7361727261792f6a736172726179)[![License](https://camo.githubusercontent.com/82faee383aec50542570e1b02ad1c2bdde23451a90bca03ea0f94c13654f6b2a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6f6d657237333336342f6a736172726179)](https://camo.githubusercontent.com/82faee383aec50542570e1b02ad1c2bdde23451a90bca03ea0f94c13654f6b2a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6f6d657237333336342f6a736172726179)[![Tests](https://camo.githubusercontent.com/18118d3f30f71541a5d62d3cb9fbfb71cde8b5f8d7766ea0d2dca68081288f36/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d3130302532422d627269676874677265656e)](https://camo.githubusercontent.com/18118d3f30f71541a5d62d3cb9fbfb71cde8b5f8d7766ea0d2dca68081288f36/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d3130302532422d627269676874677265656e)

> **Write JavaScript Array code in PHP.** Familiar, powerful, and intuitive API for working with arrays.

If you know JavaScript arrays, you already know JsArray.

---

What is JsArray?
----------------

[](#what-is-jsarray)

JsArray brings the beloved JavaScript Array methods to PHP with:

- ✅ **Familiar API** - Same methods, same behavior as JavaScript
- ✅ **Full Type Safety** - PHP 8+ with complete type hints
- ✅ **Flexible** - Choose immutable (safe) or mutable (fast) mode
- ✅ **Pure PHP** - Zero dependencies, lightweight
- ✅ **Native PHP Interoperability** - Behaves like a first-class PHP collection

---

Installation
------------

[](#installation)

```
composer require jsarray/jsarray
```

**Requirements:** PHP 8.0+

---

Quick Start
-----------

[](#quick-start)

### The Basics

[](#the-basics)

```
use JsArray\JsArray;

$numbers = JsArray::from([1, 2, 3, 4, 5]);

// Transform data
$doubled = $numbers->map(fn($number) => $number * 2);

// Keep only matching items
$evenNumbers = $numbers->filter(fn($number) => $number % 2 === 0);

// Combine operations (method chaining)
$result = $numbers
    ->filter(fn($number) => $number > 2)
    ->map(fn($number) => $number * 10)
    ->toArray();

// Result: [30, 40, 50]
```

### Working with Objects

[](#working-with-objects)

```
$users = JsArray::from([
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 17],
    ['name' => 'Charlie', 'age' => 30],
]);

// Get names of adults
$adultNames = $users
    ->filter(fn($user) => $user['age'] >= 18)
    ->map(fn($user) => $user['name'])
    ->toArray();

// Result: ['Alice', 'Charlie']
```

Flexible Callback Signatures
----------------------------

[](#flexible-callback-signatures)

Use only the parameters you need:

```
// Just the item value
$numbers->map(fn($number) => $number * 2);

// Item and its index
$items->filter(fn($item, $index) => $index > 0);
$numbers->forEach(fn($number, $index) => echo "$index: $number");

// Full context (item, index, and array reference)
$array->map(fn($item, $index, $array) =>
    $item > ($array->length / 2) ? 'big' : 'small'
);
```

JsArray automatically detects which parameters your callback uses. No configuration needed!

---

Native PHP Interoperability
---------------------------

[](#native-php-interoperability)

JsArray behaves like a **first‑class PHP collection** and integrates naturally with core language features.

### Iteration (Iterator)

[](#iteration-iterator)

Use JsArray directly in `foreach` loops:

```
$items = JsArray::from([1, 2, 3]);

foreach ($items as $value) {
    echo $value;
}
```

No conversion needed.

### ArrayAccess

[](#arrayaccess)

Use JsArray as an array:

```
$items = JsArray::from([1, 2, 3]);

echo $items[0]; // 1
$items[0] = 10;
echo $items[0]; // 10
$items->toArray(); // [10, 2, 3]
```

### Counting (Countable)

[](#counting-countable)

Use PHP’s native `count()` function:

```
$items = JsArray::from([1, 2, 3]);

echo count($items); // 3
```

Equivalent to:

```
$items->length;
```

### JSON Serialization (JsonSerializable)

[](#json-serialization-jsonserializable)

Serialize JsArray cleanly using `json_encode()`:

```
$items = JsArray::from([1, 2, 3]);

echo json_encode($items);
```

Output:

```
[1, 2, 3]
```

### Create a JsArray from a JSON string:

[](#create-a-jsarray-from-a-json-string)

```
$json = '[1, 2, 3]';
$items = JsArray::fromJson($json);

// Now you can use JsArray methods
$doubled = $items->map(fn($n) => $n * 2);
```

This makes JsArray ideal for APIs, responses, and data transport without extra mapping.

---

Core Features
-------------

[](#core-features)

**Transformation**

```
$array->map(fn($item) => $item * 2);           // Transform each item
$array->filter(fn($item) => $item > 10);       // Keep matching items
$array->reduce(fn($total, $item) => $total + $item, 0);  // Combine to single value
$array->flat();                                 // Flatten nested arrays
$array->flatMap(fn($item) => [$item, $item * 2]); // Map then flatten
```

**Search**

```
$array->find(fn($item) => $item > 100);        // Get first match
$array->findIndex(fn($item) => $item > 100);   // Get index of first match
$array->includes(50);                          // Check if value exists
$array->indexOf(50);                           // Get index of value
$array->some(fn($item) => $item > 100);        // Check if ANY match
$array->every(fn($item) => $item > 0);         // Check if ALL match
```

**Access**

```
$array->first();                               // Get first item
$array->last();                                // Get last item
$array->at(0);                                 // Get item at index
$array->at(-1);                                // Get last item (negative index)
$array->length;                                // Get array length
```

**Manipulation**

```
$array->push($item1, $item2);                  // Add items to end
$array->pop();                                 // Remove and return last item
$array->unshift($item1, $item2);               // Add items to start
$array->shift();                               // Remove and return first item
$array->slice(1, 3);                           // Extract portion
$array->reverse();                             // Reverse order
$array->sort();                                // Sort items
$array->concat($otherArray);                   // Combine arrays
$array->join(', ');                            // Join into string
```

**Other**

```
$array->keys();                               // Get all keys
$array->values();                             // Get all values
$array->toArray();                            // Convert to native PHP array
$array->forEach(fn($item) => echo $item);     // Execute for each item
$array->toImmutable();                        // Convert array to immutable
$array->toMutable();                          // Convert array to mutable
$array->getMutableCopy();                     // Create new mutable copy of array
$array->getImmutableCopy();                   // Create new immutable copy of array
```

---

Two Modes: Immutable &amp; Mutable
----------------------------------

[](#two-modes-immutable--mutable)

### Immutable Mode (Default)

[](#immutable-mode-default)

Creates a new array for each operation. Original is never changed.

```
$original = JsArray::from([1, 2, 3]);
$doubled = $original->map(fn ($n) => $n * 2);

$original->toArray(); // [1, 2, 3]
$doubled->toArray();  // [2, 4, 6]
```

**Use immutable when:**

- Processing user input
- Data safety matters
- Building complex logic
- Working with small to medium arrays (&lt; 10,000 items)

### Mutable Mode (Fast)

[](#mutable-mode-fast)

Modifies the array in-place. Much faster for large datasets.

```
$array = JsArray::mutable([1, 2, 3, 4, 5]);

$array
    ->map(fn ($n) => $n * 2)
    ->filter(fn ($n) => $n > 2);

$array->toArray(); // [4, 6, 8, 10]
```

**Use mutable when:**

- Processing large datasets (&gt; 50,000 items)
- Performance is critical
- Building or accumulating data
- Bulk operations (imports, migrations)

### Converting Between Modes

[](#converting-between-modes)

Start with immutable, convert if needed

```
$array = JsArray::from([1, 2, 3]);

if ($arraySize > 50000) {
    $array->toMutable();  // Switch to mutable mode
}
```

Create mutable copy without affecting original

```
$copy = $array->getMutableCopy();
$copy->map(...)->filter(...);
echo $array->toArray();  // Original unchanged
```

Convert back to immutable

```
$safeArray = $copy->toImmutable();
```

Check the mode:

```
$array->isMutable;    // bool
$array->isImmutable;  // bool
```

---

Testing
-------

[](#testing)

Run tests:

```
composer test
```

Tests include:

- 190+ test cases
- All methods covered
- Edge cases tested
- Immutable/mutable modes tested

---

Contributing
------------

[](#contributing)

We welcome contributions!

1. Fork the repository
2. Create a feature branch
3. Write tests for your changes
4. Ensure tests pass
5. Submit a pull request

---

Documentation Files
-------------------

[](#documentation-files)

- **[API.md](./docs/API.md)** - Complete API reference
- **[PATTERNS.md](./docs/PATTERNS.md)** - Common patterns and recipes
- **[EXAMPLES.md](./docs/EXAMPLES.md)** - Real-world usage examples
- **[PERFORMANCE.md](./docs/PERFORMANCE.md)** - Performance analysis and tips
- **[MUTABILITY.md](./docs/MUTABILITY.md)** - Deep dive into mutable/immutable modes

---

License
-------

[](#license)

MIT License - See [LICENSE](./LICENSE) for details.

---

Support
-------

[](#support)

- 🐛 [Report Issues](https://github.com/omer73364/JsArray/issues)

---

Changelog
---------

[](#changelog)

### v2.1.0

[](#v210)

##### ✨ Enhanced native PHP interoperability:

[](#-enhanced-native-php-interoperability)

- **Iteration (Iterator)**: Seamless `foreach` loop support
- **ArrayAccess**: Access elements using array syntax (e.g., `$array[0]`)
- **Counting (Countable)**: Native `count()` function integration
- **JSON Serialization (JsonSerializable)**: Direct `json_encode()` support
- **JSON Deserialization**: Create JsArray from JSON strings with `fromJson()`

### v2.0.0

[](#v200)

- ✨ Added mutable mode for performance
- ✨ 5 new methods (shift, unshift, indexOf, lastIndexOf, reverse)
- ✨ Flexible callback signatures (use only params you need!)
- ✨ Depth parameter for flat()
- 🐛 Fixed filter re-indexing for numeric arrays
- 📚 Comprehensive documentation files

### v1.0.0

[](#v100)

- Initial release

---

**JsArray** - *JavaScript Arrays in PHP*

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance82

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

4

Last Release

97d ago

Major Versions

v1.0.1 → v2.0.02026-02-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/74917221c98f22f204e89a8b60493f85fa20336a75b79adb5e4f048e4ffb5f78?d=identicon)[omer73364](/maintainers/omer73364)

---

Top Contributors

[![omer73364](https://avatars.githubusercontent.com/u/61283834?v=4)](https://github.com/omer73364 "omer73364 (31 commits)")[![pradzikowski](https://avatars.githubusercontent.com/u/1573220?v=4)](https://github.com/pradzikowski "pradzikowski (1 commits)")

---

Tags

arrayjavascriptcollectionfunctionalimmutable

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/jsarray-jsarray/health.svg)

```
[![Health](https://phpackages.com/badges/jsarray-jsarray/health.svg)](https://phpackages.com/packages/jsarray-jsarray)
```

###  Alternatives

[aimeos/map

Easy and elegant handling of PHP arrays as array-like collection objects similar to jQuery and Laravel Collections

4.2k412.9k11](/packages/aimeos-map)[athari/yalinqo

YaLinqo, a LINQ-to-objects library for PHP

4561.2M5](/packages/athari-yalinqo)[qaribou/immutable.php

Immutable, highly-performant collections, well-suited for functional programming and memory-intensive applications.

344146.0k](/packages/qaribou-immutablephp)[crell/fp

Functional utilities for PHP 8 and later

91429.8k11](/packages/crell-fp)[yansongda/supports

common components

211.4M31](/packages/yansongda-supports)[armincms/json

A Laravel Nova field.

25149.4k3](/packages/armincms-json)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
