From d3eda175c17c90c19250e4737d2eeede90aad188 Mon Sep 17 00:00:00 2001 From: Greg Dunlap <gdd@heyrocker.com> Date: Sat, 7 Jan 2012 16:36:07 +0100 Subject: [PATCH] Added drupal_array_unset_nested_value() --- core/includes/common.inc | 63 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/core/includes/common.inc b/core/includes/common.inc index 654406056ef..d29713d7966 100644 --- a/core/includes/common.inc +++ b/core/includes/common.inc @@ -6429,6 +6429,69 @@ function drupal_array_set_nested_value(array &$array, array $parents, $value, $f $ref = $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: + * @code + * // 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'), + * ); + * @endcode + * + * To deal with the situation, the code needs to figure out the route to the + * element, given an array of parents that is either + * @code array('signature_settings', 'signature') @endcode in the first case or + * @code array('signature_settings', 'user', 'signature') @endcode 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: + * @code + * // Do not do this! Avoid eval(). + * eval('unset($form[\'' . implode("']['", $parents) . '\']);'); + * @endcode + * + * Instead, use this helper function: + * @code + * drupal_array_unset_nested_value($form, $parents, $element); + * @endcode + * + * 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: + * @code + * unset($form['signature_settings']['signature']); + * @endcode + * + * @param $array + * A reference to the array to modify. + * @param $parents + * An array of parent keys, starting with the outermost key and including the + * key to be unset. + * + * @see drupal_array_set_nested_value() + */ +function drupal_array_unset_nested_value(array &$array, array $parents) { + $ref = &$array; + $unset_key = array_pop($parents); + foreach ($parents as $parent) { + $ref = &$ref[$parent]; + } + unset($ref[$unset_key]); +} + /** * Retrieves a value from a nested array with variable depth. *