valentine94
3/3/2016 - 8:11 AM

Smart array_unshift with possibility to fix the inserted value key.

Smart array_unshift with possibility to fix the inserted value key.

/**
 * Smart array_unshift with possibility to fix the inserted value key.
 *
 * @param array &$array
 *   Main array.
 * @param array $insert
 *   Array to be prepended.
 * @param string|null $key
 *   Optional param to set the specific array key for inserted array.
 */
function smart_array_unshift(array &$array, array $insert, $key = NULL) {
  array_unshift($array, $insert);
  if (!empty($key)) {
    static $old_key = '0';
    if (array_key_exists($old_key, $array)) {
      $keys = array_keys($array);
      $keys[array_search($old_key, $keys)] = $key;
      $array = array_combine($keys, $array);
    }
  }
}