Skip to content

Instantly share code, notes, and snippets.

@angry-dan
Last active December 25, 2015 16:28
Show Gist options
  • Save angry-dan/7005652 to your computer and use it in GitHub Desktop.
Save angry-dan/7005652 to your computer and use it in GitHub Desktop.
A couple of (hopefully) useful API functions that would have sat well in Drupal 7. Use them to insert an element into an array with string keys (where array_slice won't do)E.g:$element = array('dog' => 'bruce', 'elephant' => 'nelly', 'lion' => 'paws');element_insert_after($element, array('cat' => 'pussy'), 'dog') would give:array('dog' => 'bruce…
<?php
/**
* Insert an element into an associative array after a specified key.
*
* @see _element_insert()
*/
function element_insert_after(&$element, $insert, $key) {
_element_insert(TRUE, $element, $insert, $key);
}
/**
* Insert an element into an associative array before a specified key.
*
* @see _element_insert()
*/
function element_insert_before(&$element, $insert, $key) {
_element_insert(FALSE, $element, $insert, $key);
}
/**
* Insert or move an item or items in an associative array at a defined point.
*
* @param bool $after
* Set to TRUE to insert $insert AFTER $key in $element, FALSE to insert
* $insert BEFORE $key in $element.
* @param array $element
* An associative array which is to be manipulated.
* @param string|array $insert
* Either a key in $element to be moved, or a new associative array to be
* inserted.
* @param string $key
* The point within $element that $insert should be placed, such that if
* $after is TRUE, then elements within $insert will be placed immediately
* following $key.
*
*/
function _element_insert($after, &$element, $insert, $key) {
if (!is_array($insert) && isset($element[$insert])) {
$insert = array($insert => $element[$insert]);
}
$new = array();
while (list($k, $v) = each($element)) {
if ($after) {
$new[$k] = $v;
}
if ($k === $key) {
$element = $new + $insert + $element;
return;
}
if (!$after) {
$new[$k] = $v;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment