1.2.462. Find Key Directly

There is no need to use foreach() to search for a key.

PHP offers two solutions : array_search() and array_keys(). Array_search() finds the first key that fits a value, and array_keys() returns all the keys.

<?php

$array = ['a', 'b', 'c', 'd', 'e'];

print array_search($array, 'c');
// print 2 => 'c';

print_r(array_keys($array, 'c'));
// print 2 => 'c';

?>

See also array_search and array_keys.

1.2.462.1. Suggestions

  • Use array_search()

  • Use array_keys()

1.2.462.2. Specs

Short name

Structures/GoToKeyDirectly

Rulesets

All

Exakat since

1.1.4

PHP Version

All

Severity

Major

Time To Fix

Instant (5 mins)

Precision

Very high

Features

property

Available in

Entreprise Edition, Exakat Cloud