Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Reverse associative array

Tags:

arrays

php

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
like image 728
KennethC Avatar asked May 05 '26 06:05

KennethC


2 Answers

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
like image 197
phpisuber01 Avatar answered May 06 '26 18:05

phpisuber01


Simplest one is using array_search as

echo array_search('Teddy',$array); // lname
like image 41
Narendrasingh Sisodia Avatar answered May 06 '26 19:05

Narendrasingh Sisodia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!