diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index cddcde2ecc9f..1d328f4db638 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -951,4 +951,35 @@ public static function wrap($value) return is_array($value) ? $value : [$value]; } + + public static function toFilled(array $arr, $value, int $start = 0, int $end = null): array + { + $arrLength = count($arr); + + // Adjust the start position for negative values + if ($start < 0) { + $start = max(0, $arrLength + $start); + } else { + $start = min($start, $arrLength); + } + + // If end is not provided, set it to the length of the array + if (is_null($end)) { + $end = $arrLength; + } elseif ($end < 0) { + $end = max(0, $arrLength + $end); + } else { + $end = min($end, $arrLength); + } + + // Create a copy of the array to avoid modifying the original + $result = $arr; + + // Fill the array with the provided value from start to end positions + for ($i = $start; $i < $end; $i++) { + $result[$i] = $value; + } + + return $result; + } } diff --git a/tests/Support/SupportArrTest.php b/tests/Support/SupportArrTest.php index 82044805b7cb..a93ab830e24e 100644 --- a/tests/Support/SupportArrTest.php +++ b/tests/Support/SupportArrTest.php @@ -1502,4 +1502,58 @@ public function testSelect() ], ], Arr::select($array, 'name')); } + + public function testToFilledWithDefaultStartAndEnd() + { + $array = [1, 2, 3, 4, 5]; + $result = Arr::toFilled($array, '*'); + + $this->assertEquals(['*', '*', '*', '*', '*'], $result); + $this->assertEquals([1, 2, 3, 4, 5], $array); + } + + public function testToFilledWithStartIndex() + { + $array = [1, 2, 3, 4, 5]; + $result = Arr::toFilled($array, '*', 2); + + $this->assertEquals([1, 2, '*', '*', '*'], $result); + $this->assertEquals([1, 2, 3, 4, 5], $array); + } + + public function testToFilledWithStartAndEndIndices() + { + $array = [1, 2, 3, 4, 5]; + $result = Arr::toFilled($array, '*', 1, 4); + + $this->assertEquals([1, '*', '*', '*', 5], $result); + $this->assertEquals([1, 2, 3, 4, 5], $array); + } + + public function testToFilledWithNegativeIndices() + { + $array = [1, 2, 3, 4, 5]; + $result = Arr::toFilled($array, '*', -4, -1); + + $this->assertEquals([1, '*', '*', '*', 5], $result); + $this->assertEquals([1, 2, 3, 4, 5], $array); + } + + public function testToFilledWithStartGreaterThanEnd() + { + $array = [1, 2, 3, 4, 5]; + $result = Arr::toFilled($array, '*', 3, 2); + + $this->assertEquals([1, 2, 3, 4, 5], $result); // No change, start is greater than end + $this->assertEquals([1, 2, 3, 4, 5], $array); + } + + public function testToFilledWithEmptyArray() + { + $array = []; + $result = Arr::toFilled($array, '*'); + + $this->assertEquals([], $result); // No change, array is empty + $this->assertEquals([], $array); + } }