Last active
April 20, 2025 14:17
-
-
Save cameronjonesweb/05878448eb6ae401a8315a7c3aeb72b0 to your computer and use it in GitHub Desktop.
Inject an element into an array at a specific position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Inject element into an array at specific position. | |
* Works for both numeric and associative arrays. | |
* | |
* @link https://gist.github.com/cameronjonesweb/05878448eb6ae401a8315a7c3aeb72b0 | |
* | |
* @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