sanrodari
sanrodari

Reputation: 1632

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

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.

Upvotes: 1

Views: 78

Answers (3)

cha55son
cha55son

Reputation: 423

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

Upvotes: 0

halfer
halfer

Reputation: 20420

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.

Upvotes: 1

webbiedave
webbiedave

Reputation: 48897

echo print_element($array['english_values'], 'name_en');

Upvotes: 2

Related Questions