Skip to content

Instantly share code, notes, and snippets.

@scribu
Created September 20, 2010 18:53
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save scribu/588429 to your computer and use it in GitHub Desktop.
array_insert()
<?php
/**
* Insert an array into another array before/after a certain key
*
* @param array $array The initial array
* @param array $pairs The array to insert
* @param string $key The certain key
* @param string $position Wether to insert the array before or after the key
* @return array
*/
function array_insert( $array, $pairs, $key, $position = 'after' ) {
$key_pos = array_search( $key, array_keys( $array ) );
if ( 'after' == $position )
$key_pos++;
if ( false !== $key_pos ) {
$result = array_slice( $array, 0, $key_pos );
$result = array_merge( $result, $pairs );
$result = array_merge( $result, array_slice( $array, $key_pos ) );
}
else {
$result = array_merge( $array, $pairs );
}
return $result;
}
@programeriss
Copy link

programeriss commented Aug 28, 2019

// array_splice()

<?php
$input = [1,2,3];
$replacement = ['hello', 'world'];
// $slice contains the piece we extract
$slice = array_splice($input, 1, 0, $replacement);
// $input is passed by reference and so is amended
print_r($input);

//Result:
Array ( [0] => 1 [1] => hello [2] => world [3] => 2 [4] => 3 )

@jai7359
Copy link

jai7359 commented Oct 17, 2022

can u please share same thing in c language

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment