Insertar nuevo elemento en cualquier posicion de un array. FROM: http://stackoverflow.com/questions/3353745/how-to-insert-element-into-arrays-at-specific-position
// pos: Inserta despues de esta posicion
// preserve: boolean, indica si quieres conservar las claves del array
function insertNewElement($array, $element, $pos, $preserve) {
try {
if (empty($array) || empty($element)) {
throw new Exception('Faltan Datos', 1);
} else {
$pos = (isset($pos)) ? $pos : 1;
$preserve = (empty($preserve)) ? FALSE : $preserve;
return array_merge(array_slice($array, 0, $pos, $preserve),
$element,
array_slice($array, $pos, count($array) - 1, $preserve));
}
} catch (Exception $e) {
return 'Error ' . $e->getCode() . ': ' . $e->getMessage();
}
}
$array1 = array(
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'3' => 'three',
);
$array2 = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
print_r(insertNewElement($array1, array('foo'), 3, false));
echo '<br>';
print_r(insertNewElement($array2, array('key' => 'foo'), 3, false));
// Resultado by http://phpfiddle.org/
// Array ( [0] => zero [1] => one [2] => two [3] => foo [4] => three )
// Array ( [zero] => 0 [one] => 1 [two] => 2 [key] => foo [three] => 3 )