diff --git a/README.md b/README.md index 18b4f12..ab041a6 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Import any function with `use function Equip\Arr\func;`. ### List of functions -`exists($source, $key)` check if a key exists in an array. +`exists($source, $keys)` check if a key or keys exist in an array. `to_array($value)` convert a value to an array. diff --git a/src/array.php b/src/array.php index a01b91d..d46fd0b 100644 --- a/src/array.php +++ b/src/array.php @@ -5,16 +5,19 @@ use Traversable; /** - * Check if a key exists in an array. + * Check if a key or keys exist in an array. * * @param array|Traversable $array - * @param string|integer $key + * @param string|integer|array $keys * * @return boolean */ -function exists($array, $key) +function exists($array, $keys) { - return array_key_exists($key, to_array($array)); + $keys = to_array($keys); + + $intersection = array_intersect_key(to_array($array), array_flip($keys)); + return count($intersection) === count($keys); } /** diff --git a/tests/ArrayTest.php b/tests/ArrayTest.php index d63f38c..44edb95 100644 --- a/tests/ArrayTest.php +++ b/tests/ArrayTest.php @@ -156,6 +156,29 @@ public function testTail() $this->assertSame(['c'], tail($this->list)); } + public function testExists() + { + // Works with single keys + $this->assertTrue(exists($this->hash, 'company')); + $this->assertTrue(exists($this->list, 1)); + $this->assertFalse(exists($this->hash, 'missing')); + $this->assertFalse(exists($this->list, 10)); + + // Works with arrays of keys + $this->assertTrue(exists($this->hash, ['company', 'owner'])); + $this->assertTrue(exists($this->list, [0, 2])); + + // False if not all keys are present + $this->assertFalse(exists($this->hash, ['company', 'missing'])); + $this->assertFalse(exists($this->list, [0, 10])); + + // Works with empty arrays + $this->assertFalse(exists([], 'missing')); + $this->assertFalse(exists([], 10)); + $this->assertFalse(exists([], ['missing', 'also missing'])); + $this->assertTrue(exists([], [])); + } + public function testToArray() { // Works with arrays