diff --git a/src/key.php b/src/key.php index fc3ebe6..b6c9193 100644 --- a/src/key.php +++ b/src/key.php @@ -15,5 +15,7 @@ */ function key($value, $coll, $default = null) { - return array_search($value, $coll) ? : $default; + $key = array_search($value, $coll); + + return false !== $key ? $key : $default; } diff --git a/tests/KeyTest.php b/tests/KeyTest.php index 881d669..591455c 100644 --- a/tests/KeyTest.php +++ b/tests/KeyTest.php @@ -2,7 +2,6 @@ namespace Lambdish\Phunctional\Tests; -use ArrayIterator; use PHPUnit_Framework_TestCase; use function Lambdish\Phunctional\key; @@ -31,4 +30,28 @@ public function it_should_return_the_default_value_provided_if_the_key_does_not_ $this->assertSame('three', key(3, $actual, 'three')); } + + /** @test */ + public function it_should_return_empty_string_if_the_key_does_is_empty() + { + $actual = ['one' => 1, 'two' => 2, '' => 3]; + + $this->assertSame('', key(3, $actual, 'default')); + } + + /** @test */ + public function it_should_return_the_value_of_the_item_of_an_existent_boolean_key() + { + $actual = ['one' => 1, 'two' => false]; + + $this->assertSame('two', key(false, $actual, 'default')); + } + + /** @test */ + public function it_should_return_first_occurrence_of_the_item_of_an_existent_key() + { + $actual = [false => 1]; + + $this->assertSame(0, key(1, $actual, 'default')); + } }