开发者

Find the key of a corresponding array value

开发者 https://www.devze.com 2022-12-10 02:48 出处:网络
I have an array like this. What i want is to get the value of the index for specific values. ie, i want to know the index 开发者_Python百科of the value \"UD\" etc.

I have an array like this. What i want is to get the value of the index for specific values. ie, i want to know the index 开发者_Python百科of the value "UD" etc.

Array
(
    [0] => LN
    [1] => TYP
    [2] => UD
    [3] => LAG
    [4] => LO
)

how can i do that??


array_search function is meant for that usage

snipet:

$index = array_search('UD', $yourarray);
if($index === false){ die('didn\'t found this value!'); }
var_dump($index);


Use array_search:

$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');

$key = array_search('UD', $array); // $key = 2;
if ($key === FALSE) {
  // not found
}


Your best bet is:

array_keys() returns the keys, numeric and string, from the input array.

If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned.

$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');
print_r(array_keys($array, "UD"));

Array
(
    [0] => 2
)

Possible considerations for not using array_search()

array_search() If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.


I suggest array_flip:

$value = "UD";
$new = array_flip($arr);
echo "result: " . $new[$value];


Just a note: some of these array_* functions are substantially more useful in PHP 5.3 with the addition of anonymous functions. You can now do things like:

$values = array_filter($userArray, function($user)
{
   // If this returns true, add the current $user object to the resulting array
   return strstr($user->name(),"ac");
});

Which will return all elements in our imaginary array of user objects that contain "ac" ("Jack","Jacob") in their name.

This has been possible in the past with create function, or simply by defining a function beforehand, but this syntax make it a lot more accessible.

http://ca2.php.net/manual/en/functions.anonymous.php


$array = Array(0 => LN, 1 => TYP, 2 => UD, 3 => LAG, 4 => LO);
$arrtemp = array_keys($array,'UD');
echo 'Result : '.$arrtemp[0];

I use array_keys to find it.

0

精彩评论

暂无评论...
验证码 换一张
取 消