简体   繁体   中英

What is the reverse of (object) array (key => value) in PHP?

Is there a fast way to return a key when you know its value in PHP?

For example, if you have:

$Numbers = (object) array ( "0" => 0, "1" => 1, "2" => 3, "3" => 7, "4" => 13 );

is there a way to return:

echo re(13);   // Print 4 

One way I could think of is to build a function specifically for this, but I was wondering if there is a better way.

There is array_search :

$key = array_search(13, (array) $Numbers);

See http://ua2.php.net/array_search

As several other people have mentioned, array_search does what you asked. But if you want an array of ALL the keys that contain the value instead of only the first, you can use array_keys .

print_r(array_keys($Numbers, 13)); // print Array ( [0] => 4 )

http://www.php.net/manual/en/function.array-keys.php

http://php.net/array_search

echo array_search($valToSearch, (array) $Numbers);

if you are certain that you have unique keys:

$flipped = array_flip($array);
$key = $flipped[$knownValue];
return $key;

Otherwise, use array_search:

return array_search($knownValue, $array);

The first approach may be better if you do a number of lookups, and have unique values. The second approach returns the first matching key in case of multiple values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM