Last active
July 23, 2024 18:53
-
-
Save petenelson/4571e0d85ebd3f361523dfa8faabfc27 to your computer and use it in GitHub Desktop.
PHP: Insert item into an array
This file contains 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 | |
/** | |
* Inserts an item into an array. | |
* | |
* @param array $array The array to insert into. | |
* @param mixed $key The array key to insert the item at, either before or after. | |
* @param mixed $new_key The new array key. | |
* @param mixed $new_item The new item to insert. | |
* @param bool $before Insert before or after? | |
* @return array | |
*/ | |
function insert_into_array( $array, $key, $new_key, $new_item, $before = true ) { | |
if ( ! is_array( $array ) || empty( $key ) || empty( $new_key ) ) { | |
return $array; | |
} | |
if ( ! array_key_exists( $key, $array ) ) { | |
$array[ $new_key ] = $new_item; | |
return $array; | |
} | |
$new_array = []; | |
foreach ( array_keys( $array ) as $array_key ) { | |
if ( $before && $array_key == $key ) { | |
$new_array[ $new_key ] = $new_item; | |
} | |
$new_array[ $array_key ] = $array[ $array_key ]; | |
if ( ! $before && $array_key === $key ) { | |
$new_array[ $new_key ] = $new_item; | |
} | |
} | |
return $new_array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment