Skip to content

Instantly share code, notes, and snippets.

@cameronjonesweb
Created March 18, 2022 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronjonesweb/05878448eb6ae401a8315a7c3aeb72b0 to your computer and use it in GitHub Desktop.
Save cameronjonesweb/05878448eb6ae401a8315a7c3aeb72b0 to your computer and use it in GitHub Desktop.
Inject an element into an array at a specific position
<?php
/* Returns:
array(5) {
["red"]=>
string(3) "Red"
["green"]=>
string(5) "Green"
["purple"]=>
string(6) "Purple"
["blue"]=>
string(4) "Blue"
["yellow"]=>
string(6) "Yellow"
}
*/
$input = array(
"red" => "Red",
"green" => "Green",
"blue" => "Blue",
"yellow" => "Yellow",
);
cameronjonesweb_inject_into_array( $input, array( 'purple' => 'Purlple' ), 2 );
/* Returns:
array(5) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
[2]=>
string(4) "blue"
[3]=>
string(6) "purple"
[4]=>
string(6) "yellow"
}
*/
$input = array("red", "green", "blue", "yellow");
cameronjonesweb_inject_into_array( $input, 'purple', 3 );
<?php
/**
* Inject element into an array at specific position.
* Works for both numeric and associative arrays.
*
* @param array $array Target array to inject into.
* @param mixed $to_inject Element to inject.
* @param int $position Position to inject into.
* @return array
*/
function cameronjonesweb_inject_into_array( $array, $to_inject, $position ) {
$start = array_slice( $array, 0, $position );
$end = array_slice( $array, $position );
if ( ! is_array( $to_inject ) ) {
$to_inject = array( $to_inject );
}
return array_merge( $start, $to_inject, $end );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment