How to find the array index key of multi-dimensional array

array_search() is a built in PHP function that searches the array for a given value and returns the first corresponding key if successful.

Syntax

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

Support: (PHP 4 >= 4.0.5, PHP 5, PHP 7)

$needle

  • The $needle parameter is required.
  • It refers to the value that needs to be searched in the array.

$haystack

  • The $haystack parameter is required.
  • It refers to the original array, on which search operation is performed.

$strict

  • The $haystack parameter is an optional one.
  • It can be set to true or false, and refers to the strictness of search.
  • The default value of this parameter is false.
  • Example: when it is set to true, the string 45 is not same as number 45.

Return Values

  • The key of a value is returned if it is found in an array, otherwise false.
  • If the value is found in the array more than once, the first matching key is returned.

Example #1 – Search an array for the value “Jerusalem” and return its key

$records = [
  'New Delhi' => 'India',
  'Madrid' => 'Spain',
  'Israel' => 'Jerusalem',
  'Amsterdam' => 'Netherlands'
];
$countries = array_search("Jerusalem", $records);
print_r($countries);
The above example will output:
Israel

Example #2 – With third parameter “strict” mode

$records = [
  'x' => '10',
  'y' => 10,
  'z' => '10'
];
echo 'Without strict parameter: ';
echo array_search(10, $records);
echo 'With strict parameter: ';
echo array_search(10, $records, true);
The above example will output
Israel

Example #3 – You don’t have to write your own function to search through a multidimensional array, (example with array_column())

$records = [
    [
        'id' => 12,
        'country' => 'India',
        'capital' => 'New Delhi',
    ],
    'Spain' => [
        'id' => 24,
        'country' => 'Spain',
        'capital' => 'Madrid',
    ],
    [
        'id' => 91,
        'country' => 'Israel',
        'capital' => 'Jerusalem',
    ],
    'Netherlands' => [
        'id' => 121,
        'country' => 'Netherlands',
        'capital' => 'Amsterdam',
    ]
];
$countries = array_column($records, 'country');
print_r($countries);
$key = array_search('Israel', array_column($records, 'country'));
echo 'Key: ' . $key;
The above example will output
Array
(
    [0] => India
    [1] => Spain
    [2] => Israel
    [3] => Netherlands
)
Key: 2

Hope you find this helpful

Parimal Ghadiyali
Parimal Ghadiyali

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳