Monday, 2 February 2015

Insert At Array Index


<?php
/**
 *
 * @insert a new array member at a given index
 *
 * @param array $array
 *
 * @param mixed $new_element
 *
 * @param int $index
 *
 * @return array
 *
 */
function insertArrayIndex($array, $new_element, $index) {
 
/*** get the start of the array ***/
 
$start = array_slice($array, 0, $index); 
 
/*** get the end of the array ***/
 
$end = array_slice($array, $index);
 
/*** add the new element to the array ***/
 
$start[] = $new_element;
 
/*** glue them back together and return ***/
 
return array_merge($start, $end);
 }
?>

EXAMPLE USAGE


<?php

$index 
= 3;
$new_element = 'steve irwin';
$array = array('platypus', 'wallaby', 'koala', 'dingo', 'wombat');
$new_array = insertArrayIndex($array, $new_element, $index);
print_r( $new_array );
?>

0 comments:

Post a Comment