Skip to content

Instantly share code, notes, and snippets.

@otakupahp
Last active February 9, 2020 10:17
Show Gist options
  • Save otakupahp/39d24f4c4e3f17b86c0e7fe42cc87f9c to your computer and use it in GitHub Desktop.
Save otakupahp/39d24f4c4e3f17b86c0e7fe42cc87f9c to your computer and use it in GitHub Desktop.
Insert an element before and after certain array key of an associative array
<?php
/**
* Insert an element before certain array key of an associative array.
* If no key is found,the element will be inserted at the end
*
* @since 1.0.0
*
* @param array $origin The original array where the element will be inserted
* @param mixed $element The element to insert
* @param string $key The key that will be searched to insert the element before.
* @return array
*/
private function insert_element_before($origin, $element, $key) {
# Get key position
$keys = array_keys( $origin );
$index = array_search( $key, $keys, true );
$pos = false === $index ? count( $origin ) : $index;
return array_merge( array_slice( $origin, 0, $pos ), $element, array_slice( $origin, $pos ) );
}
/**
* Insert an element after certain array key of an associative array.
* If no key is found, the element will be inserted at the end
*
* @since 1.0.0
*
* @param array $origin The original array where the element will be inserted
* @param mixed $element The element to insert
* @param string $key The key that will be searched to insert the element before.
* @return array
*/
private function insert_element_after($origin, $element, $key) {
# Get key position
$keys = array_keys( $origin );
$index = array_search( $key, $keys, true );
$pos = false === $index ? count( $origin ) : $index + 1;
return array_merge( array_slice( $origin, 0, $pos ), $element, array_slice( $origin, $pos ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment