Core\Arr::hasKey
Core\Arr::hasKey(array<T> $a, int|uint|string $key): boolCore\Arr::hasKey( array<T> $a, int|uint|string $key, ): bool
Tests whether an array has an entry stored under a key.
The result is true when the key is present, whatever is stored under it. A key whose value is null is still present. Use Core\Arr::hasKey to tell a stored null from a key that is not in the array.
The key is an int, a uint or a string. 1 and "1" are the same key. In a plain list the keys are the positions, so 0 names the first entry.
Good to know: this looks at the keys, never at the values. Use Core\Arr::contains to search the values instead.
Parameters
$aarray<T>The array to look in.$keyint|uint|stringThe key, anint, auintor astring.1and"1"name one entry.
Return value
Returns bool. true when the key is present, whatever its value is.
Changelog
| Version | Change |
|---|---|
0.0.6 | A Core\Arr function that takes a key, such as hasKey, gave a compile error for a uint key (an unsigned whole number). It now takes a uint key, as $a[$key] already did. So Core\Arr::fillKeys($ids, true) works when $ids is a list of uint values. |
Examples
A setting the request sent
<?nvs// Shows how to test whether an array has an entry under a key.
array<string> $query = ['sort' => 'price', 'view' => 'grid'];
// The key "sort" is there. This prints yes.echo Core\Arr::hasKey($query, 'sort') ? 'yes' : 'no', "\n";
// The key "page" is not there. This prints no.echo Core\Arr::hasKey($query, 'page') ? 'yes' : 'no', "\n";yesnoOne key written two ways
<?nvs// Shows that a whole number and the text of that number are one key. The// method looks at the keys, so the values do not matter.
array<string> $rows = [1 => 'first', 2 => 'second'];
// The key was written as the number 1, and "1" names the same entry. This prints yes.echo Core\Arr::hasKey($rows, '1') ? 'yes' : 'no', "\n";
// The number 2 names the entry written as 2. This prints yes.echo Core\Arr::hasKey($rows, 2) ? 'yes' : 'no', "\n";
// "first" is a value, not a key. This prints no.echo Core\Arr::hasKey($rows, 'first') ? 'yes' : 'no', "\n";yesyesnoA value for a setting nobody sent
<?nvs// Shows how a page reads settings out of a request. Where the request sent// nothing, the page uses its own value instead.
array<string> $query = ['sort' => 'price'];
// The request sent "sort". This prints price.echo Core\Arr::hasKey($query, 'sort') ? $query['sort'] : 'name', "\n";
// The request sent no "view", so the page uses "grid". This prints grid.echo Core\Arr::hasKey($query, 'view') ? $query['view'] : 'grid', "\n";pricegrid