I’m working with large nested associative arrays in PHP and I need to apply transformations (like map, filter, reshape) immutably, meaning the original array should not be modified.
The problem is that every time I use array_map or array_filter, PHP creates a new array copy, which becomes very slow and memory-heavy for large datasets.
For example:
$data = [
'users' => [
['id' => 1, 'name' => 'Alice', 'active' => true],
['id' => 2, 'name' => 'Bob', 'active' => false],
]];
$mapped = array_map(fn($u) => ['id' => $u['id']], $data['users']);
$filtered = array_filter($mapped, fn($u) => $u['id'] % 2 === 0);
This works but copies arrays multiple times. On large inputs, it’s slow and inefficient.
Main question: What is the most efficient way in PHP to transform nested arrays immutably without repeatedly creating deep copies?