From ff1c4c38e682f4175486abfb5cb97d83681b659c Mon Sep 17 00:00:00 2001 From: Oluwatobi Omisakin Date: Tue, 30 Apr 2024 19:04:30 +0300 Subject: [PATCH] feat: Add array search --- src/Traits/ArrayPrefix.php | 11 +++++++++++ tests/ArrayPrefixTraitTest.php | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/Traits/ArrayPrefix.php b/src/Traits/ArrayPrefix.php index 9b74f64..7327930 100644 --- a/src/Traits/ArrayPrefix.php +++ b/src/Traits/ArrayPrefix.php @@ -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 diff --git a/tests/ArrayPrefixTraitTest.php b/tests/ArrayPrefixTraitTest.php index 37f49ea..1a0451f 100644 --- a/tests/ArrayPrefixTraitTest.php +++ b/tests/ArrayPrefixTraitTest.php @@ -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), + ); + } }