Mavichow
Mavichow

Reputation: 1223

Grab Multi-Dimensional Array's Key using Value

I got an Array...

$arrays = array(
    'image'    => array('jpg','jpeg','png'),
    'document' => array('pdf','docx','pptx'),
);

And here is my extension variable

$ext = 'jpg';

I wanted to achieve is, using this variable $ext I need to loop and compare which Keys from the multi dimension $arrays and final output return to me as image

Currently I got a solution myself is by using 2 foreach loop to loop & match :

$type = null;
foreach($arrays as $key=>$arr)
{

    foreach($arr as $k=>$a)
    {
        if($a==$ext)
        {
            $type =  $key;
        }
    }
}

echo $type;

I'm PHP beginner & wanted to know , does PHP array function has better solution to grab the Key in multi-dimensional array with a value instead of looping it?

Upvotes: 0

Views: 35

Answers (1)

kamal pal
kamal pal

Reputation: 4207

You can create a custom function, which will return you the expected result, and by creating function, you can use it n number of times you need, see below :-

function getDataType($ext, $typesArray)
{
  foreach ($typesArray as $key => $types) {
    if (in_array($ext, $types)) {
      return $key;
    }
  }
}
$arrays = array(
    'image'    => array('jpg','jpeg','png'),
    'document' => array('pdf','docx','pptx'),
);
$ext = 'jpg';
echo getDataType($ext, $arrays);

Upvotes: 1

Related Questions