Problem/Motivation
One of the most difficult things about manipulating Drupal forms is the process of manipulating the arrays themselves. And one of the things that I commonly want to do is "stick this stuff in after that". But I have yet to find a PHP function to manipulate arrays in this way.
So I wrote this function called array_insert(). Perhaps there's a cleaner way to handle this, but it seems like a function that should be available in Drupal core. It would certainly help with a lot of common hook_form_alter() tasks.
For instance, this function (finally) offers a way to stick something into the node-type settings page (admin/settings/content-types/[node-type]) immediately before the "submit" buttons, you'd just create an array with your form items and then call
$form = array_insert($form, 'buttons', $my_stuff, TRUE);
/**
* Inserts values from $arr2 after (or before) $key in $arr1
* if $key is not found, $arr2 is appended to $arr1 using array_merge()
*
* @param $arr1
* array to insert into
* @param $key
* key of $arr1 to insert after
* @param $arr2
* array whose values should be inserted
* @param $before
* insert before the given key. defaults to inserting after
* @return
* merged array
*/
function array_insert($arr1, $key, $arr2, $before = FALSE){
$done = FALSE;
foreach($arr1 as $arr1_key => $arr1_val){
if(!$before){
$new_array[$arr1_key] = $arr1_val;
}
if($arr1_key == $key && !$done){
foreach($arr2 as $arr2_key => $arr2_val){
$new_array[$arr2_key] = $arr2_val;
}
$done = TRUE;
}
if($before){
$new_array[$arr1_key] = $arr1_val;
}
}
if(!$done){
$new_array = array_merge($arr1, $arr2);
}
return $new_array;
}
Steps to reproduce
N/A
Proposed resolution
Introduce new utility class for addressing the problem.
Remaining tasks
Review
Commit
User interface changes
N/A
Introduced terminology
N/A
API changes
N/A
Data model changes
N/A
Release notes snippet
N/A