function drupal_array_get_nested_value

Retrieves a value from a nested array with variable depth.

This helper function should be used when the depth of the array element being retrieved may vary (that is, the number of parent keys is variable). It is primarily used for form structures and renderable arrays.

Without this helper function the only way to get a nested array value with variable depth in one line would be using eval(), which should be avoided:

// Do not do this! Avoid eval().
// May also throw a PHP notice, if the variable array keys do not exist.
eval('$value = $array[\'' . implode("']['", $parents) . "'];");

Instead, use this helper function:

$value = drupal_array_get_nested_value($form, $parents);

The return value will be NULL, regardless of whether the actual value is NULL or whether the requested key does not exist. If it is required to know whether the nested array key actually exists, pass a third argument that is altered by reference:

$key_exists = NULL;
$value = drupal_array_get_nested_value($form, $parents, $key_exists);
if ($key_exists) {

  // ... do something with $value ...
}

However if the number of array parent keys is static, the value should always be retrieved directly rather than calling this function. For instance:

$value = $form['signature_settings']['signature'];

Parameters

$array: The array from which to get the value.

$parents: An array of parent keys of the value, starting with the outermost key.

$key_exists: (optional) If given, an already defined variable that is altered by reference.

Return value

The requested nested value. Possibly NULL if the value is NULL or not all nested parent keys exist. $key_exists is altered by reference and is a Boolean that indicates whether all nested parent keys exist (TRUE) or not (FALSE). This allows to distinguish between the two possibilities when NULL is returned.

See also

drupal_array_set_nested_value()

drupal_array_unset_nested_value()

22 calls to drupal_array_get_nested_value()
ArrayUnitTest::testGet in drupal/core/modules/system/lib/Drupal/system/Tests/Common/ArrayUnitTest.php
Tests getting nested array values.
drupal_validate_form in drupal/core/includes/form.inc
Validates user-submitted form data in the $form_state array.
field_add_more_js in drupal/core/modules/field/field.form.inc
Ajax callback: Responds to a new empty widget being added to the form.
field_add_more_submit in drupal/core/modules/field/field.form.inc
Form submission handler for the "Add another item" button of a field form.
field_form_get_state in drupal/core/modules/field/field.form.inc
Retrieves processing information about a field from $form_state.

... See full list

File

drupal/core/includes/common.inc, line 6159
Common functions that many Drupal modules will need to reference.

Code

function &drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
  return NestedArray::getValue($array, $parents, $key_exists);
}