How to find key from value

73 Views Asked by At

I've got 2 arrays

$amen=Array ( [0] => 1 [1] => 5 [2] => 2 [3] => 8 [4] => 9 [5] => 7) 

$amenArr=Array ( [1] => Array ( [en] => Air conditioning [th] => เครื่องปรับอากาศ ) [5] => Array ( [en] => Balcony/terrace [th] => ระเบียง/ทางเดิน ) [2] => Array ( [en] => Hair dryer [th] => ไดรเป่าผม ) [8] => Array ( [en] => Internet access (FREE) [th] => อินเตอร์เน็ต (ฟรี) ) [9] => Array ( [en] => Kitchen [th] => ห้องครัว ) [7] => Array ( [en] => Refrigerator [th] => ตู้เย็น ) [6] => Array ( [en] => Satellite/cable TV [th] => ดาวเทียม/เคเบิ้ลทีวี ) [4] => Array ( [en] => Shower Hot/Cool [th] => เครื่องทำน้ำอุ่น ) [3] => Array ( [en] => Television LCD/LED [th] => โทรทัศน์ LCD/LED ) )

And I want to show the facility from $amen value so I use array_key_exists but it's not work.

            foreach($amenArr as $key=>$val){
                if(array_key_exists($amen,$amenArr)){
                    echo "<input type=\"checkbox\" name=\"rtype_amen[]\" value=\"$key\" id=\"amen-$key\" checked/><label for=\"amen-$key\">&nbsp;".$amenArr[$key]['en']."</label><br />";
                }else{
                    echo "<input type=\"checkbox\" name=\"rtype_amen[]\" value=\"$key\" id=\"amen-$key\" /><label for=\"amen-$key\">&nbsp;".$amenArr[$key]['en']."</label><br />";
                }
            }

Is there anyway to make this work?

2

There are 2 best solutions below

0
On BEST ANSWER

just use if( isset( $amen[$key] ))

foreach($amenArr as $key=>$val){
    if( isset( $amen[$key] )){
        echo "<input type=\"checkbox\" name=\"rtype_amen[]\" value=\"$key\" id=\"amen-$key\" checked/><label for=\"amen-$key\">&nbsp;".$amenArr[$key]['en']."</label><br />";
    }else{
        echo "<input type=\"checkbox\" name=\"rtype_amen[]\" value=\"$key\" id=\"amen-$key\" /><label for=\"amen-$key\">&nbsp;".$amenArr[$key]['en']."</label><br />";
    }
}
0
On

Accordingly to php documentation, the first parameter of the method array_key_exists should be the key, i.e. a string or number, but you are passing the entire $amen array.

I presume that what you desire is something like this:

foreach($amen as $key=>$val){
    if(array_key_exists($val,$amenArr)){
         //First logic here
    }else{
         //second logic here
    }
}