-1

What's the best/fastest way to get the keys of an array by a search of a value in the 2nd level arrays?

$test = array(
    'name_01' => array('yellow', 'red', 'blue', 'black', 'white', 'purple'),
    'name_02' => array('red', 'blue', 'white', 'green'),
    'name_03' => array('blue', 'pink', 'purple', 'blue'),
    'name_04' => array('white', 'black', 'red'),
    'name_05' => array('yellow', 'white', 'pink', 'black')
);

For example the search by pink should return array('name_03', 'name_05')

Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71
Phantom
  • 638
  • 1
  • 7
  • 18
  • one `foreach()` is enough – Alive to die - Anant May 09 '18 at 10:55
  • 2
    Sorry, but “what is the best way to do X” questions to me always translate to _“I’ve done eff all to try and solve this myself; instead I now expect you to list all possible ways, and could you also rank them for me while you’re at it”_ - to which the answer is, nope, sorry, you need to make your own efforts first. Please go read [ask]. – CBroe May 09 '18 at 10:56
  • @CBroe I don't get your complain. To keep the question as short as possible, I did not include my own solution (foreach() with in_array()). https://stackoverflow.com/questions/6661530/php-multidimensional-array-search-by-value => I thought there might be a better/shorter/faster solution using a php-function I might not know of. – Phantom May 09 '18 at 11:16
  • Well if we don’t know what your current solution is, how could we possibly tell if anything else was perhaps faster or not? _“To keep the question as short as possible”_ - who or what gave you the idea that _that_ was the main goal you should aspire to with your question in the first place? – CBroe May 09 '18 at 11:19

2 Answers2

3

A simple foreach() with in_array() is enough

$search = 'pink';

foreach($test as $key=>$arr){
   if(in_array($search,$arr)){
     echo $key.PHP_EOL;
   }

}

Output : https://3v4l.org/HVem8

If you want array as an output : https://3v4l.org/8e0sj

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
2

you can use in_array()

$test = array(
    'name_01' => array('yellow', 'red', 'blue', 'black', 'white', 'purple'),
    'name_02' => array('red', 'blue', 'white', 'green'),
    'name_03' => array('blue', 'pink', 'purple', 'blue'),
    'name_04' => array('white', 'black', 'red'),
    'name_05' => array('yellow', 'white', 'pink', 'black')
);

print_r(find_keys($test, 'pink'));

function find_keys($arr, $find){
    $keys = array();
    foreach ($arr as $key => $value) {
        if (!in_array($find, $value)) {
            continue;
        }
        $keys[] = $key;
    }

    return $keys;
}

https://eval.in/1001516

Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71