diff --git a/packages/support/src/Arr/ManipulatesArray.php b/packages/support/src/Arr/ManipulatesArray.php index d300c5bd7..eb487e91e 100644 --- a/packages/support/src/Arr/ManipulatesArray.php +++ b/packages/support/src/Arr/ManipulatesArray.php @@ -324,6 +324,32 @@ public function intersectKeys(array|self ...$arrays): self return $this->createOrModify(namespace\intersect_keys($this->value, ...$arrays)); } + /** + * Returns a new instance of the array, with only key=>value pairs from the first array where the key matches the values + * from the second array; a wrapper around intersectKeys with an array_flip for convenience. + * + * @param array|static ...$arrays + * + * @return static + */ + public function withKeys(array|self ...$arrays): self + { + return $this->createOrModify(namespace\intersect_keys($this->value, array_flip(...$arrays))); + } + + /** + * Returns a new instance of the array, without the key=>value pairs from the first array where the key matches the values + * from the second array; a wrapper around diffKeys with an array_flip for convenience. + * + * @param array|static ...$arrays + * + * @return static + */ + public function withoutKeys(array|self ...$arrays): self + { + return $this->createOrModify(namespace\diff_keys($this->value, array_flip(...$arrays))); + } + /** * Merges the array with the given arrays. * diff --git a/packages/support/tests/Arr/ManipulatesArrayTest.php b/packages/support/tests/Arr/ManipulatesArrayTest.php index f1150610e..eade280b6 100644 --- a/packages/support/tests/Arr/ManipulatesArrayTest.php +++ b/packages/support/tests/Arr/ManipulatesArrayTest.php @@ -574,6 +574,42 @@ public function test_intersect_keys(): void $this->assertSame($expected, $current); } + public function test_with_keys(): void + { + $collection = arr([ + 'first_name' => 'John', + 'last_name' => 'Doe', + 'age' => 42, + ]); + $current = $collection + ->withKeys(['first_name', 'last_name']) + ->toArray(); + $expected = [ + 'first_name' => 'John', + 'last_name' => 'Doe', + ]; + + $this->assertSame($expected, $current); + } + + public function test_without_keys(): void + { + $collection = arr([ + 'first_name' => 'John', + 'last_name' => 'Doe', + 'age' => 42, + ]); + $current = $collection + ->withoutKeys(['age']) + ->toArray(); + $expected = [ + 'first_name' => 'John', + 'last_name' => 'Doe', + ]; + + $this->assertSame($expected, $current); + } + public function test_unique_with_basic_item(): void { $collection = arr([