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), + ); + } }