Skip to content

Instantly share code, notes, and snippets.

@iprodev
Last active December 29, 2018 14:37
Show Gist options
  • Save iprodev/c1b70ebf268ca4d9eee3cdc03464cd83 to your computer and use it in GitHub Desktop.
Save iprodev/c1b70ebf268ca4d9eee3cdc03464cd83 to your computer and use it in GitHub Desktop.
PHP : Replace the contents of two or more arrays together into the first array with default properties.
<?php
/**
* Replace the contents of two or more arrays together into the first array with default properties.
*
* @param array $default The array to replace. It will receive the new properties.
* @param array $arrayN An array containing additional properties to merge in.
* @return array
*/
function array_replace_default() {
$arguments = func_get_args();
if ( count( $arguments ) < 2 )
throw new Exception( sprintf( '"%s" must contain at least 2 arguments.', __FUNCTION__ ) );
$default = isset( $arguments[0] ) ? $arguments[0] : array();
$arrays = array_slice( $arguments, 1 );
foreach ( $arrays as $array ) {
$default = array_replace( $default, array_intersect_key( $array, $default ) );
}
return $default;
}
/**
* Replace the contents of two or more arrays together into the first array recursively with default properties.
*
* @param array $default The array to replace. It will receive the new properties.
* @param array $arrayN An array containing additional properties to merge in.
* @return array
*/
function array_replace_default_deep() {
$arguments = func_get_args();
if ( count( $arguments ) < 2 )
throw new Exception( sprintf( '"%s" must contain at least 2 arguments.', __FUNCTION__ ) );
$default = isset( $arguments[0] ) ? $arguments[0] : array();
$arrays = array_slice( $arguments, 1 );
foreach ( $arrays as $array ) {
$default = array_replace_recursive( $default, array_intersect_key( $array, $default ) );
}
return $default;
}
// Example
$default = array(
"a" => "green",
"b" => array(
"id" => 1
)
);
$array1 = array(
"a" => "green",
"b" => array(
"ids" => 1
),
"yellow",
"red"
);
$array2 = array(
"a" => "blue",
"b" => array(),
"navy",
"red"
);
$result_normal = array_replace_default( $default, $array1, $array2 );
$result_deep = array_replace_default_deep( $default, $array1, $array2 );
echo "<pre>";
echo "Normal Arrays Extend:\n";
print_r($result_normal);
echo "\nDeep Arrays Extend:\n";
print_r($result_deep);
echo "</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment