Discover an array key by the given value?

Asked

Viewed 508 times

4

I wish that through a given value I could return the array key. Example:

$array = array("primeiro" => 1, "segundo" => 2, "terceiro" => 3);

to find out if the value exists in the array there is the function in_array(); but to find out the key of the array to which that value belongs? how can I do this in a simple way? using the given example, using the given value '1', find the key "first".

1 answer

6


Use the function array_search(), given a value if found it returns the corresponding array key.

demo

<?php
$arr = array("primeiro" => 1, "segundo" => 2, "terceiro" => 3);
$chave = array_search('1', $arr);

echo $chave;

Exit:

primeiro

Browser other questions tagged

You are not signed in. Login or sign up in order to post.