FlyingCat
FlyingCat

Reputation: 14270

How to get the array value based on the key?

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

I have

$array1{
 '0' =>'text1',
 '1' =>'text2',
 '2' =>'text3'
}


$array2{
 '0' =>'123',
 '1' =>'456',
 '2' =>'789'
}

 //$source could be text1,text2 or text3
 //I want to show 123, 456 or 789 based on the value passed in
       if(in_array($source, $array1)){
         $id=array_keys($array1,$source);
         echo $array2[$id];
       }

I got an error saying 'illegal offset type' becasue of $array2[$id].

Are there anyways to fix this? Thanks a lot!

Upvotes: 1

Views: 6461

Answers (3)

Daniel
Daniel

Reputation: 4946

$array1 = array('0' => 'text1', '1' => 'text2', '2' => 'text3');
$array2 = array('0' => '123', '1' => '456', '2' => '789');

$source = "text2";

foreach ($array1 as $key => $value) {

    if ($value === $source) {
        echo "value = " . $array2[$key];
    }

}

output: value = 456

Upvotes: 2

DiverseAndRemote.com
DiverseAndRemote.com

Reputation: 19888

I think you need array_search. Try:

if($id = array_search($source, $array1))
     echo $array2[$id];

Upvotes: 3

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

Use array_search instead of array_keys. You want the first key that has the value of $source, not an array with all keys that have the value.

Upvotes: 1

Related Questions