Skip to content

Commit

Permalink
Merge pull request #32 from transprime-research/feat-add-array-search
Browse files Browse the repository at this point in the history
feat: Add array search
  • Loading branch information
omitobi authored Apr 30, 2024
2 parents a3c66e4 + ff1c4c3 commit a76d0be
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Traits/ArrayPrefix.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,17 @@ public function walkRecursive(callable $callable, $arg = null)
return $this->setResult($workableItem);
}

public function search($needle, bool $strict = true, $default = null)
{
$result = array_search($needle, $this->getWorkableItem(), $strict);

if ($result === false) {
return $default;
}

return $result;
}


/**
* Like php array_key_exists, this instead search if (one or more) keys exists in the array
Expand Down
22 changes: 22 additions & 0 deletions tests/ArrayPrefixTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -247,4 +247,26 @@ public function testTail(): void

arrayed([])->tail();
}

public function testSearch(): void
{
$data = ['a', 'b', 'c', 'd'];

$this->assertSame(
1,
arrayed($data)->search('b'),
);

// When there is no matching value.
$this->assertEquals(
null,
arrayed($data)->search('z'),
);

// With default value.
$this->assertEquals(
false,
arrayed($data)->search('z', true, false),
);
}
}

0 comments on commit a76d0be

Please sign in to comment.