Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/support/src/Arr/ManipulatesArray.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<TKey, TValue>|static<TKey, TValue> ...$arrays
*
* @return static<TKey, TValue>
*/
public function onlyKeys(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<TKey, TValue>|static<TKey, TValue> ...$arrays
*
* @return static<TKey, TValue>
*/
public function exceptKeys(array|self ...$arrays): self
{
return $this->createOrModify(namespace\diff_keys($this->value, array_flip(...$arrays)));
}

/**
* Merges the array with the given arrays.
*
Expand Down
36 changes: 36 additions & 0 deletions packages/support/tests/Arr/ManipulatesArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,42 @@ public function test_intersect_keys(): void
$this->assertSame($expected, $current);
}

public function test_only_keys(): void
{
$collection = arr([
'first_name' => 'John',
'last_name' => 'Doe',
'age' => 42,
]);
$current = $collection
->onlyKeys(['first_name', 'last_name'])
->toArray();
$expected = [
'first_name' => 'John',
'last_name' => 'Doe',
];

$this->assertSame($expected, $current);
}

public function test_except_keys(): void
{
$collection = arr([
'first_name' => 'John',
'last_name' => 'Doe',
'age' => 42,
]);
$current = $collection
->exceptKeys(['age'])
->toArray();
$expected = [
'first_name' => 'John',
'last_name' => 'Doe',
];

$this->assertSame($expected, $current);
}

public function test_unique_with_basic_item(): void
{
$collection = arr([
Expand Down
Loading