[ create a new paste ] login | about

Link: http://codepad.org/1u1ZfxJ7    [ raw code | output | fork ]

PHP, pasted on Jan 9:
<?php

function inject_array( &$array, array $var, $pos = null )
{
   $tmp_storage = array();
   $pos         = (int) $pos;

   if ( $pos > count( $array ) )
   {
      foreach ( $var as $key => $value )
      {
         $array[] = $value;
      }

      return;
   }

   if ( array_key_exists( $pos, $array ) )
   {
      $tmp_storage = array_slice( $array, $pos );
   }

   $injection_position = $pos;

   foreach ( $var as $key => $value )
   {
      $array[ $injection_position ] = $value;
      ++$injection_position;
   }

   $pos        = $pos + count( $var );
   $new_length = $pos + count( $tmp_storage );

   for ( $i = $pos, $j = 0; $i < $new_length; $i++, $j++ )
   {
      $array[ $i ] = $tmp_storage[ $j ];
   }
}

$sample = array(
   'test',
   'test1',
   'test2',
);

inject_array( $sample, array( 'test4', 'test5' ), 1 );

var_dump( $sample ); exit;


Output:
1
2
3
4
5
6
7
8
9
10
11
12
array(5) {
  [0]=>
  string(4) "test"
  [1]=>
  string(5) "test4"
  [2]=>
  string(5) "test5"
  [3]=>
  string(5) "test1"
  [4]=>
  string(5) "test2"
}


Create a new paste based on this one


Comments: