0

I am trying to get the key of an array based on the value.

$array1=array(
'0'=>'test1',
'1'=>'test2',
'2'=>'test3',
'3'=>'test1'
)

$array2=array(
'0'=>'11',
'1'=>'22',
'2'=>'33',
'3'=>'44'
)

I have

$source is the needle. it could be 'test1', 'test2' or 'test3'

for loop to get different $source string

   if(in_array($source[$i], $array1)){
      $id=array_search($source[$i],$array1);
      //I want to output 11, 22 or 33 based on $source
      //However, my $array1 has duplicated value.
      //In my case, if $source is test1, the output will be 11,11 instead of 11 and 44

      echo $array2[$id]);
   }

I am not sure how to fix this. My brain is fried. Thanks for the help!

2 Answers 2

2

PHP has a function for this: http://php.net/manual/en/function.array-keys.php

i.e. $keys = array_keys( $myArray, $theValue ); and to get just the first: $keys[0];

1

This should work.

$array3 = array_flip(array_reverse($array1, true));
$needle = $source[$i];
$key = $array3[$needle];
echo $array2[$key];

What array_flip does is exchange the keys and values. In case of duplicate values, only the last pair will be exchanged. To counter this, we use array_reverse but we preserve the key structure.

Edit : For more clarification, here's a dry run.

$array1=array(
'0'=>'test1',
'1'=>'test2',
'2'=>'test3',
'3'=>'test1'
)

After array_reverse($array1, true) the output will be

array(
'3' => 'test1',
'2' => 'test3',
'1' => 'test2',
'0' => 'test1'
)

Now, when we flip this, the output will be

array(
'test1' => '0', //would be 3 initially, then overwritten by 0
'test2' => '1',
'test3' => '2',
)
2
  • Thanks for your tip! But after reading the manual of array_flip() I would says array_flip is not a good idea for most applications as only strings or numbers are allowed as values. However in this case it will work
    – hek2mgl
    Feb 8, 2013 at 20:59
  • Yes, but in this case, the values themselves, are Strings. It will not work on array of Objects, or Arrays for that matter.
    – Achrome
    Feb 8, 2013 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.