Score:-1

How do I use `NestedArray::getValue()` to get a value from an array?

et flag

I see the NestedArray::getValue() but the documentation isn't clear. How do I use this to get a value out of a nested array, such as form state or raw form input?

Score:2
et flag

If you have an array like this:

$my_array = [
  'key1' => [
    'key1.1' => 'a',
    'key1.2' => 'b',
    'key1.3' => 'c',
  ],
  'key2' => [
    'key2.1' => 'x',
    'key2.2' => 'y',
    'key2.3' => 'z',
  ],
];

And you want to get to $my_array['key2']['key2.2'] dynamically (e.g., using an array of #parents from a form element), you can use NestedArray::getValue($my_array, ['key2', 'key2.2']).

As a bonus, this method returns a reference to the value so you can also change what you get back and the change will be reflected in the array.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.