There is a code Code: $data["red"] = array("abc","def","ghi"); $data["blue"] = array("jul"); $data["green"] = array("mno","pqr","stu"); $data["yellow"] = array(); how can i get "green" key using "pqr" ? i tried using array_search, but it doesn't work Code: echo array_seach(array("pqr"),$data); //Result: NONE working code is Code: foreach($data as $key => $a){ foreach($a as $b){ echo $key."-".$b."\n"; } } but, i don't wanna use foreach (loop) please tell me. thank you for reading and answering.
I don't think you can get a value from a key without knowing the key. Maybe reverse the values Or try: PHP: for($i = 0; $i < 3; $i++){ if(in_array("whateveruwanttocheck", $data[$i])){ //your code }}
Here is my point: You are trying to get array key with known value. PHP: foreach($data as $key => $value) { if($value == "pqr") { return $key; // Yea, you got that "green" }}
If you don't want to use a for/foreach loop, I think you should rewrite what you're doing in an efficient way. Structure your array in such a way that you won't require looping through it. You can use array_filter, though it's said a foreach loop would be much faster. PHP: $keys = array_keys(array_filter(function(array $array) : bool{ return in_array("pqr", $array);}, $data));var_dump($keys); Try benchmarking that with a foreach loop. PHP: foreach($data as $key => $array){ if(array_search("pqr", $array, true) !== false){ break; } $key = null;}var_dump($key);
FYI: If you need which way is faster, here the explanation: First, foreach method has 0(n), Second, array_search also has 0(n). And I can said @musqit ways are slower than others. He used foreach and also array_search. As my experience (also I did some research), in_array was very worst if your array has big values. If you need faster way, you can use Binary Search method if known data are use-able with it. EDITED: This argument are only for non-array values.
You are kidding, right? Please tell me you are. All other methods by others don't work at all. Including yours!
That isn't my point. You say my method is the slowest while your method doesn't even work. Id rather choose slow over not working at all. Plus you haven't given any examples to support your "binary search" methodology.
Create a flipped mapping from "pqr" to "green". Create a data structure class for it if it is too hard to maintain.