0

In PHP how can I pass on an identifier to a function to retrieve a value from a multi-dimensional array? With the below function, how can I return 'Female', using the $identifier variable?

function phrase($identifier) {
  $lang = array();
  $lang['settings']    = 'Personal settings';
  $lang['entergender'] = 'Please select your gender';
  $lang['gender']['m'] = 'Male';
  $lang['gender']['f'] = 'Female';

  return $lang[$identifier];
}

phrase('gender/f');//obviously this won't work
bart
  • 14,958
  • 21
  • 75
  • 105
  • 2
    pretty similar http://stackoverflow.com/questions/27929875/how-to-write-getter-setter-to-access-multi-leveled-array-by-dot-separated-key-na – Kevin Dec 01 '15 at 01:53

1 Answers1

1

You could write a variadic function to request in multiple array dimensions. You would then call your function with each dimension's key as an argument.

The code below uses func_num_args() and func_get_arg() to iterate over the arguments passed to the function.

function phrase() {
  $lang = array();
  $lang['settings']    = 'Personal settings';
  $lang['entergender'] = 'Please select your gender';
  $lang['gender']['m'] = 'Male';
  $lang['gender']['f'] = 'Female';
  $lang['foo']['bar']['baz'] = 'Hello!';

  $val = $lang;
  for ($i = 0; $i < func_num_args(); $i++) {
    $val = $val[func_get_arg($i)];
  }

  return $val;
}

print phrase('settings');
print phrase('gender', 'f');
print phrase('foo', 'bar', 'baz');
cmrn
  • 1,105
  • 6
  • 14