function drupal_array_set_nested_value

Sets a value in a nested array with variable depth.

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


// Assume you have a 'signature' element somewhere in a form. It might be:
$form['signature_settings']['signature'] = array(
  '#type' => 'text_format',
  '#title' => t('Signature'),

// Or, it might be further nested:
$form['signature_settings']['user']['signature'] = array(
  '#type' => 'text_format',
  '#title' => t('Signature'),

To deal with the situation, the code needs to figure out the route to the element, given an array of parents that is either


in the first case or


in the second case.

Without this helper function the only way to set the signature element in one line would be using eval(), which should be avoided:

// Do not do this! Avoid eval().
eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');

Instead, use this helper function:

drupal_array_set_nested_value($form, $parents, $element);

However if the number of array parent keys is static, the value should always be set directly rather than calling this function. For instance, for the first example we could just do:

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


$array: A reference to the array to modify.

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

$value: The value to set.

$force: (Optional) If TRUE, the value is forced into the structure even if it requires the deletion of an already existing non-array parent value. If FALSE, PHP throws an error if trying to add into a value that is not an array. Defaults to FALSE.

See also


7 calls to drupal_array_set_nested_value()
drupal_validate_form in drupal/includes/
Validates user-submitted form data in the $form_state array.
field_form_set_state in drupal/modules/field/
Stores processing information about a field in $form_state.
file_field_widget_submit in drupal/modules/file/
Form submission handler for upload/remove button of file_field_widget_form().
file_managed_file_submit in drupal/modules/file/file.module
Form submission handler for upload / remove buttons of managed_file elements.
form_process_machine_name in drupal/includes/
Processes a machine-readable name form element.

... See full list


drupal/includes/, line 6774
Common functions that many Drupal modules will need to reference.


function drupal_array_set_nested_value(array &$array, array $parents, $value, $force = FALSE) {
  $ref =& $array;
  foreach ($parents as $parent) {

    // PHP auto-creates container arrays and NULL entries without error if $ref
    // is NULL, but throws an error if $ref is set, but not an array.
    if ($force && isset($ref) && !is_array($ref)) {
      $ref = array();
    $ref =& $ref[$parent];
  $ref = $value;