function drupal_array_unset_nested_value

Unsets 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.

Example:

// 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

array(
  'signature_settings',
  'signature',
);

in the first case or

array(
  'signature_settings',
  'user',
  'signature',
);

in the second case.

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

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

Instead, use this helper function:

drupal_array_unset_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:

unset($form['signature_settings']['signature']);

Parameters

$array: A reference to the array to modify.

$parents: An array of parent keys, starting with the outermost key and including the key to be unset.

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

See also

drupal_array_set_nested_value()

drupal_array_get_nested_value()

1 call to drupal_array_unset_nested_value()
ArrayUnitTest::testUnset in drupal/core/modules/system/lib/Drupal/system/Tests/Common/ArrayUnitTest.php
Tests unsetting nested array values.

File

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

Code

function drupal_array_unset_nested_value(array &$array, array $parents, &$key_existed = NULL) {
  NestedArray::unsetValue($array, $parents, $key_existed);
}