Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using array_search for multi value search

Tags:

php

  $array_subjected_to_search =array(
  array(
          'name' => 'flash',
          'type' => 'hero'
      ),

  array(
          'name' => 'zoom',
          'type' => 'villian'
      ),

  array(
          'name' => 'snart',
          'type' => 'antihero'
      ),
  array(
        'name' => 'flash',
        'type' => 'camera'
      )
  );
  $key = array_search('flash', array_column($array_subjected_to_search, 'name'));
  var_dump($array_subjected_to_search[$key]);

This works fine, but is there a way to search using multiple values: eg. get key where name='flash' && type='camera' ?

like image 765
eozzy Avatar asked Sep 18 '26 20:09

eozzy


2 Answers

is there a way to search using multiple values: eg. get key where name='flash' && type='camera' ?

Simply with array_keys function:

$result_key = array_keys($array_subjected_to_search, [ 'type' => 'camera','name' => 'flash']);
print_r($result_key);

The output:

Array
(
    [0] => 3
)
like image 173
RomanPerekhrest Avatar answered Sep 21 '26 08:09

RomanPerekhrest


The array_search function accepts an array as parameters the following will work for the use case you provided.

$array_subjected_to_search =array(
  array(
    'name' => 'flash',
    'type' => 'hero'
  ),
  array(
    'name' => 'zoom',
    'type' => 'villian'
  ),
  array(
    'name' => 'snart',
    'type' => 'antihero'
  ),
  array(
    'name' => 'flash',
    'type' => 'camera'
  )
);
$compare = array(
    'name'=>'flash',
    'type'=>'camera'
);
$key = array_search($compare, $haystack);
var_dump($haystack[$key]);

Note: your current search will not function correctly it will always return the zero index because the array_search returns 0 or false.

$key = array_search('flash', array_column($array_subjected_to_search, 'name'));
var_dump($array_subjected_to_search[$key]);
like image 41
James Ray Avatar answered Sep 21 '26 08:09

James Ray