Search code examples
phparraysmultidimensional-arrayarray-key

PHP i can't figure out how to find the array key of current parent array?


I have an assoc. multidimensional array and a function:

// input:

$array = array();
$array['keyname0'] = array(
  'key0' => 'value0',
  'key1' => 'value1',
  //etc,
);
$array['keyname1'] = array(
  'key0' => 'value0',
  'key1' => 'value1',
  //etc,
);

// method:

function getCurrentParentArrayKey($array){
  //should return current key name of this array
  //I can't for the life of me find any array function on php.net or anywhere that solves this
}

// execute:

print getCurrentParentArrayKey($array['keyname0']);

// output:

keyname0

a better example might be:

$users=array(
  'michael' => array(
    'age' => '28',
    'height' => '5\'9"',
  )
);

function getUserName($array){
  //do something
  //@return: 'michael'
}

print getUserName($users['michael']);

Solution

  • You could add the parent key as a value of your array:

    array(
        'key1' => array(
             'subkey1' => 'value1',
             'subkey2' => 'value2',
             'subkey3' => 'value3',
             'keyinparent' => 'key1'
        ),
        'key2' => array(
             'subkey4' => 'value4',
             'subkey5' => 'value5',
             'subkey6' => 'value6',
             'keyinparent' => 'key2'
        )
    )
    

    It requires processing before you pass the sub-array to the function though.