How to access to an element in a PHP multidimensional array with a string?

Go To StackoverFlow.com

1

I have something like this:

function print_element($array, $field){
  return "Element: {$array[$field]}";
}

$array['name_en'] = 'English name';
echo print_element($array, 'name_en');

I wish to access a property within an array that belongs to the main array like this:

$array['english_values']['name_en'] = 'English name';
echo print_element($array, "['english_values']['name_en']");

Is there a way to accomplish this?

Thx in advance.

2012-04-03 21:54
by sanrodari
If your function doesn't return anything, you don't need to call echo before it. Your function handles the echo internally - Sampson 2012-04-03 22:03


2

echo print_element($array['english_values'], 'name_en');
2012-04-03 21:58
by webbiedave


1

Pass just the string 'english_values,name_en' to your function. Inside the function, explode the string on the comma, then loop through the array and assign $array = $array[$thisKey] on each pass. You may also wish to check that it is_array($array) on each pass.

2012-04-03 22:00
by halfer


0

You have the array and also the keys try this:

    function print_var($val) {
        echo "VAR: {$val} <br/>";
    }

    $array['english_values']['name_en'] = 'English name';
    print_var($array['english_values']['name_en']);

    // OUTPUT
    // VAR: English name
2012-04-03 22:09
by cha55son
Ads