Thursday, 30 August 2018

PHP - Invert the associative array

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


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

0 comments:

Post a Comment