Core\Arr::keyOf
Core\Arr::keyOf(array<T> $haystack, T $needle): ?stringCore\Arr::keyOf( array<T> $haystack, T $needle, ): ?string
Finds the key of the first entry that holds a value.
The key is returned as text, whatever the array uses. In a list the keys are the positions, so the first entry gives "0". When no entry holds the value the result is null. There is no false to tell apart from a key of zero, which is the mistake array_search is known for.
Only the first entry is found. When two entries hold the same value, the one that was put in first is the one you get.
The value is compared exactly, the same way Core\Arr::contains compares it. Core\Arr::contains is the member to use when you only want to know whether the value is there at all.
Parameters
$haystackarray<T>The array to search.$needleTThe value to look for, compared ascontainscompares.
Return value
Returns ?string. The key as a string, or null when no entry is identical. It never returns false.
Examples
Where is this tag
<?nvs// Shows how to find the key of the entry that holds a value.
array<string> $tags = ['sale', 'new', 'gift'];
// "new" is the second entry, so its key is 1. This prints 1.echo Core\Arr::keyOf($tags, 'new'), "\n";
// The key is always text, so you can print it or store it as text.string $key = Core\Arr::keyOf($tags, 'gift') ?? '';echo 'gift is stored under ', $key, "\n";1gift is stored under 2The first entry wins
<?nvs// Shows which entry is found when two entries hold the same value, and what// you get when no entry holds it.
array<string> $seats = ['a1' => 'free', 'a2' => 'taken', 'a3' => 'free'];
// Two seats are free. The first one is found, so this prints a1.echo Core\Arr::keyOf($seats, 'free'), "\n";
// No seat is broken. The result is `null`, and `??` replaces it with your own// text. This prints none.echo Core\Arr::keyOf($seats, 'broken') ?? 'none', "\n";a1noneWhich route has this path
<?nvs// Shows how a program finds the name of a route when it only has the path.
array<string> $routes = ['home' => '/', 'help' => '/help', 'shop' => '/products'];
array<string> $visited = ['/help', '/cart'];
foreach ($visited as string $path) { // The name is `null` when no route has this path, so `??` gives the page // a name to log instead. echo $path, ' -> ', Core\Arr::keyOf($routes, $path) ?? 'unknown', "\n";}/help -> help/cart -> unknown