Add helper methods to inject items into a particular position in associative arrays

Created on 30 May 2006, over 18 years ago
Updated 6 September 2024, 5 months ago

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

✨ Feature request
Status

RTBC

Version

11.0 πŸ”₯

Component
BaseΒ  β†’

Last updated about 2 hours ago

Created by

πŸ‡ΊπŸ‡ΈUnited States jjeff

Live updates comments and jobs are added and updated live.
  • API addition

    Enhances an existing API or introduces a new subsystem. Depending on the size and impact, possibly backportable to earlier major versions.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024