Skip to content

Commit

Permalink
Fixed array merge with empty arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
ElGigi committed May 3, 2021
1 parent fa50fbf commit f040d97
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file. This projec
to [Semantic Versioning] (http://semver.org/). For change log format,
use [Keep a Changelog] (http://keepachangelog.com/).

## [1.1.6] - 2021-05-03

### Fixed

- Array merge with empty arrays

## [1.1.5] - 2021-04-25

### Changed
Expand Down
9 changes: 9 additions & 0 deletions src/ArrayHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,15 @@ public static function toXml($array, ?SimpleXMLElement $root = null, ?string $ro
public static function mergeRecursive(array $arraySrc, array ...$arrays): array
{
foreach ($arrays as $array) {
if (empty($array)) {
continue;
}

if (empty($arraySrc)) {
$arraySrc = $array;
continue;
}

if (self::isSequential($arraySrc) || self::isSequential($array)) {
$arraySrc = array_merge($arraySrc, $array);
continue;
Expand Down
29 changes: 29 additions & 0 deletions tests/ArrayHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class ArrayHelperTest extends TestCase
{
public function testIsSequential()
{
$this->assertTrue(ArrayHelper::isSequential([]));
$this->assertTrue(ArrayHelper::isSequential(['foo', 'bar', 'hello', 'world']));
$this->assertTrue(ArrayHelper::isSequential([0 => 'foo', 1 => 'bar', 2 => 'hello', 3 => 'world']));
$this->assertTrue(ArrayHelper::isSequential([0 => 'foo', 2 => 'bar', 1 => 'hello', 3 => 'world']));
Expand Down Expand Up @@ -121,6 +122,34 @@ public function testMergeRecursive()
],
ArrayHelper::mergeRecursive($arr1, $arr5)
);

$this->assertEquals(
[
321 => '321 value',
'foo' => 'foo value',
'bar' => 'bar value',
123 => '123 value',
],
ArrayHelper::mergeRecursive(
['321' => '321 value'],
[],
['foo' => 'foo value', 'bar' => 'bar value', '123' => '123 value'],
[],
)
);
$this->assertEquals(
[
'foo' => 'foo value',
'bar' => 'bar value',
123 => '123 value',
321 => '321 value',
],
ArrayHelper::mergeRecursive(
[],
['foo' => 'foo value', 'bar' => 'bar value', '123' => '123 value'],
['321' => '321 value'],
)
);
}

public function testTraverseExists()
Expand Down

0 comments on commit f040d97

Please sign in to comment.