Created
November 7, 2015 13:04
-
-
Save wpscholar/0deadce1bbfa4adb4e4c to your computer and use it in GitHub Desktop.
Insert a value or key/value pair after a specific key in an array. If key doesn't exist, value is appended to the end of the 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 | |
/** | |
* Insert a value or key/value pair after a specific key in an array. If key doesn't exist, value is appended | |
* to the end of the array. | |
* | |
* @param array $array | |
* @param string $key | |
* @param array $new | |
* | |
* @return array | |
*/ | |
function array_insert_after( array $array, $key, array $new ) { | |
$keys = array_keys( $array ); | |
$index = array_search( $key, $keys ); | |
$pos = false === $index ? count( $array ) : $index + 1; | |
return array_merge( array_slice( $array, 0, $pos ), $new, array_slice( $array, $pos ) ); | |
} |
Great Job!
$index = array_search( $key, $keys );
Passing in true
as a third argument ensures that a strict key search is performed, especially for associative arrays:
$index = array_search( $key, $keys, $strict = true );
thanks for this
function push_at_to_associative_array($array, $key, $new ){
$keys = array_keys( $array );
$index = array_search( $key, $keys, true );
$pos = false === $index ? count( $array ) : $index + 1;
$array = array_slice($array, 0, $pos, true) + $new + array_slice($array, $pos, count($array) - 1, true);
return $array;
}
Use Case
$your_updated_orignal_parent_array = push_at_to_associative_array($your_orignal_parent_array, $orignal_parent_array_key, $new_child_single_or_multidimentional_array );
Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage.
Code below will add phone type field into woocommerce checkout billing fields array after
billing_phone
field.