views:

86

answers:

6
+1  Q: 

PHP array problem

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 of the value "UD" etc.

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

how can i do that??

+2  A: 

I suggest array_flip:

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

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
}
Dominic Rodger
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. Check out my answer
Lizard
+6  A: 

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);
RageZ
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. Check out my answer (array_keys())
Lizard
+3  A: 

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.

Lizard
A: 

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

Koobz
A: 
$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.

abu aisyah