You are here

function advagg_insert_into_array_at_key in Advanced CSS/JS Aggregation 7.2

Insert element into an array at a specific key location.

Parameters

array $input_array: The original array.

array $insert: The element that is getting inserted; array(key => value).

string $target_key: The key name.

int $location: After is 1 , 0 is replace, -1 is before.

Return value

array The new array with the element merged in.

2 calls to advagg_insert_into_array_at_key()
advagg_relocate_js_post_alter in advagg_relocate/advagg_relocate.module
Alter the js array.
advagg_relocate_js_script_rewrite in advagg_relocate/advagg_relocate.module
Add external.

File

./advagg.module, line 6144
Advanced CSS/JS aggregation module.

Code

function advagg_insert_into_array_at_key(array $input_array, array $insert, $target_key, $location = 1) {
  $output = array();
  $new_value = reset($insert);
  $new_key = key($insert);
  foreach ($input_array as $key => $value) {
    if ($key === $target_key) {

      // Insert before.
      if ($location == -1) {
        $output[$new_key] = $new_value;
        $output[$key] = $value;
      }

      // Replace.
      if ($location == 0) {
        $output[$new_key] = $new_value;
      }

      // After.
      if ($location == 1) {
        $output[$key] = $value;
        $output[$new_key] = $new_value;
      }
    }
    else {

      // Pick next key if there is an number collision.
      if (is_numeric($key)) {
        while (isset($output[$key])) {
          $key++;
        }
      }
      $output[$key] = $value;
    }
  }

  // Add to array if not found.
  if (!isset($output[$new_key])) {

    // Before everything.
    if ($location == -1) {
      $output = $insert + $output;
    }

    // After everything.
    if ($location == 1) {
      $output[$new_key] = $new_value;
    }
  }
  return $output;
}