Question

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.

Was it helpful?

Solution 2

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',
  ),
)

OTHER TIPS

I guess you mean:

$result = array();
$value1 = 'value1';
foreach($lang['lbl_mylabel1'] as $la)
{
   if(in_array($value1)) 
   {
      $result[] = $la;
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top