Repository navigation
Conversation
Use array_replace() to preserve numeric keys when merging flattened nested arrays. Renumbering could overwrite an earlier value when a later input reused the resulting numeric key. Add regression cases and update the helper documentation and changelog.
Ribeiro-MD
left a comment
There was a problem hiding this comment.
Nice, minimal fix. The bug comes from array_merge() renumbering integer keys in both arrays, so any top-level numeric key already in $flattened got reindexed as soon as a nested array was merged in. The recursive call always returns string keys ("1.name", etc.), so array_replace() is the right tool: it keeps existing keys and order, appends new ones, and for string-key collisions it still lets the later value win, same as before. The three new provider cases (non-sequential keys, a list with a nested array, negative keys with an empty array) cover the interesting shapes well, and the array<array-key, mixed> PHPDoc update matches the real return type.
A couple of small thoughts:
This changes output for existing callers. Someone who relied on the old reindexing (e.g. treating the result of flattening a list as a fresh 0..n list) will now see the original keys. It's clearly a bug fix, but it might deserve a line under the changelog's behaviour-change / BC notes rather than only under bug fixes, so upgrades aren't surprised.
It may be worth one case with a non-empty $id prefix and a numeric top-level key, e.g. array_flatten_with_dots([3 => ['a' => 1], 4 => 'x'], 'p.'), to lock in that prefixed numeric keys come out as 'p.3.a' / 'p.4' strings and aren't affected by the change.
Description
array_flatten_with_dots()usedarray_merge()when adding flattened nested arrays. This renumbered numeric keys already in the result and could cause data loss. For example,[5 => 'first', 'nested' => ['name' => 'john'], 0 => 'last']lost'first'because its key became0and was subsequently overwritten.Use
array_replace()to retain numeric keys while preserving the existing replacement behavior for string keys. Add three regression cases for sparse keys, a mixed list, and negative keys with empty arrays and falsey values. Update PHPDoc, the user guide, and the 4.7.7 changelog.Validation
vendor/bin/phpunit --no-coverage tests/system/Helpers/ArrayHelperTest.php: 42 tests, 56 assertions passed on PHP 8.5.12.git diff --check: passed.Checklist: