FlyingCat
FlyingCat

Reputation: 14270

How to search unique array key?

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!

Upvotes: 0

Views: 74

Answers (2)

Achrome
Achrome

Reputation: 7821

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',
)

Upvotes: 1

runspired
runspired

Reputation: 2693

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];

Upvotes: 2

Related Questions