smviswa
smviswa

Reputation: 111

PHP Array Search with key values

I have following arrays :

<?php 
$a=array(
    "abc"=>array("red","white","orange"),
    "def"=>array("green","vilot","yellow"),
    "xyz"=>array("blue","dark","pure")
); 

echo array_search(array("dark"),$a);

?>

How to get output of xyz in array list.

Upvotes: 1

Views: 56

Answers (3)

dhi_m
dhi_m

Reputation: 1265

Please try this

function searchMultiArray($arrayVal,$val){
    foreach($arrayVal as $key => $suba){

        if (in_array($val, $suba)) {
         return $key;
     }

 }
}

$a = array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
echo $keyVal = searchMultiArray($a , "dark");

Upvotes: 0

B. Desai
B. Desai

Reputation: 16436

You can create one user-define function to check value

 $a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure")); 
 function search_data($value, $array) {
   foreach ($array as $key => $val) {
       if(is_array($val) && in_array($value,$val))
       {
           return $key;
       }
   }
   return null;
}
echo search_data("dark",$a);

DEMO

Upvotes: 1

IsThisJavascript
IsThisJavascript

Reputation: 1716

array_search returns false or the key. Since you have multiple dimensions you must loop through to get the lowest level.

Since we are in another dimension your return will actually be 1. For this reason, if array_search succeeds we must use the key that is defined in the foreach

<?php
$a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure")); 
foreach($a as $key=>$data){
    if(array_search("dark",$data)){
        echo $key;

    }    

}

Outputs: xyz

Upvotes: 1

Related Questions