简体   繁体   中英

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!

I think you need array_search . Try:

if($id = array_search($source, $array1))
     echo $array2[$id];
$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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM