Avatar ·

How to get the key of the first row of a two-dimensional array containing the searched value?

Hello everyone! I'm new to PHP and have been struggling with this task for two hours. I have a two-dimensional array (array of rows with user data):

\n\n
$users = [\n    ['id' => 101, 'name' => 'Ivan', 'role' => 'admin'],\n    ['id' => 102, 'name' => 'Maria', 'role' => 'editor'],\n    ['id' => 103, 'name' => 'Petr', 'role' => 'admin'],\n    ['id' => 104, 'name' => 'Anna', 'role' => 'user']\n];
\n\n

I need to find the first level key (row index) of the record where name equals 'Maria'. That is, I want to get 1 (the index of the second row).

\n\n

I tried using array_search, but it only works with one-dimensional arrays. I attempted to write a loop, but it turns out cumbersome. Is there an elegant way to do this without a bunch of nested