Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Last active April 20, 2017 15:44
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 fjarrett/508e9bba8db300868a46 to your computer and use it in GitHub Desktop.
Save fjarrett/508e9bba8db300868a46 to your computer and use it in GitHub Desktop.
Recursively replace elements from passed arrays into the first array (safe for PHP 5.2)
<?php
/**
* Recursively replace elements from passed arrays into the first array (safe for PHP 5.2).
*
* @author Frankie Jarrett <fjarrett@gmail.com>
* @link http://php.net/manual/en/function.array-replace-recursive.php
*
* @param array $array1
* @param array $array2
* @param array $...
*
* @return array
*/
function safe_array_replace_recursive( array $array1, array $array2 ) {
if ( function_exists( 'array_replace_recursive' ) ) {
$args = func_get_args();
return call_user_func_array( 'array_replace_recursive', $args );
}
$result = array();
for ( $i = 0, $total = func_num_args(); $i < $total; $i++ ) {
$_array = func_get_arg( $i );
foreach ( $_array as $key => &$value ) {
if ( is_array( $value ) && isset( $result[ $key ] ) && is_array( $result[ $key ] ) ) {
$result[ $key ] = call_user_func( __FUNCTION__, $result[ $key ], $value );
continue;
}
$is_assoc = ( array_keys( $_array ) !== range( 0, count( $_array ) - 1 ) );
if ( ! $is_assoc && ! in_array( $value, $merged, true ) ) {
$result[] = $value;
continue;
}
$result[ $key ] = $value;
}
}
return (array) $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment