Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
11 changes: 7 additions & 4 deletions src/array.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down
23 changes: 23 additions & 0 deletions tests/ArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down