3

I want to get the value of the index that it's associated with.

Let's say I have an 'fname' => 'Bear' Then I receive a recieve an input from the user with a value of 'Bear' I want to Identify the data through the use of association, is it possible to build an array that looks like this 'fname' <=> 'Bear ? If yes, can you give me some example on how to use it?

this is my PHP code

$array = array('lname'=>'Teddy', 'fname' => 'Bear'); 

 $user_input = 'Teddy';
 echo $array[$user_input]; // I want this to give me the value of lname
                           // because lname is associated with Teddy
2
  • 1
    array_search()? Commented Sep 2, 2015 at 13:35
  • Or array_keys: echo array_keys($array, $user_input)[0]; See demo Commented Sep 2, 2015 at 13:41

2 Answers 2

3

One possible solution is to use array_flip

$array = array('lname'=>'Teddy', 'fname' => 'Bear');

$user_input = "Teddy";

$flipped = array_flip($array);

echo $flipped[$user_input]; // lname
Sign up to request clarification or add additional context in comments.

1 Comment

Cool. Never heard of it. Thanks bro.
3

Simplest one is using array_search as

echo array_search('Teddy',$array); // lname

2 Comments

This is much more efficient as it does not require you to copy the array like in my answer.
Yes it is but none less yours one is an alternative to the answer. @phpisuber01

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.