0

I've an associative array like this.

$lang['lbl_mylabel1'] = array('key1' => 'value1');
$lang['lbl_mylabel2'] = array('key2' => 'value1');
$lang['lbl_mylabel3'] = array('key3' => 'value1');
$lang['lbl_mylabel4'] = array('key4' => 'value2');
$lang['lbl_mylabel5'] = array('key5' => 'value3');

And I have a variable named value1 through which I want to compare values of the sub-array and return all those elements whose values are value1.

So how can I use array_intersect or any possible efficient method to return me the elements of $lang array with values1.

The answer of above code should be the first 3 elements in the $lang array.

Nikola
  • 2,093
  • 3
  • 22
  • 43
Mj1992
  • 3,404
  • 13
  • 63
  • 102

2 Answers2

2

I guess you mean:

$result = array();
$value1 = 'value1';
foreach($lang['lbl_mylabel1'] as $la)
{
   if(in_array($value1)) 
   {
      $result[] = $la;
   }
}
Yami
  • 1,405
  • 1
  • 11
  • 16
  • the `$lang` array contains around 600 elements , so I am trying to avoid loops on it. I want to compare a values with the values of the items in the `sub-array` that is assigned to the $lang array. – Mj1992 Jan 16 '14 at 09:38
0

The following code will preserve the structure of original $lang array:

$find = 'value1';
$result = array_filter($lang, function($rec) use ($find) {
    return in_array($find, $rec);
});

Where $result will be:

array (
  'lbl_mylabel1' => 
  array (
    'key1' => 'value1',
  ),
  'lbl_mylabel2' => 
  array (
    'key2' => 'value1',
  ),
  'lbl_mylabel3' => 
  array (
    'key3' => 'value1',
  ),
)
Sergiy Sokolenko
  • 5,967
  • 35
  • 37
  • excellent , Sergiy thnx . actually more of my focus was to use a built in function rather than looping on it myself. – Mj1992 Jan 16 '14 at 09:50