Created
May 31, 2022 02:27
-
-
Save phoopee3/804368e931ae4d86c187f7ef5ceed9ee to your computer and use it in GitHub Desktop.
trying to merge arrays in various ways
This file contains hidden or 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 | |
function my_merge( $a, $d ) { | |
foreach ( $d as $name => $default ) { | |
if ( array_key_exists( $name, $a ) && !is_null($a[ $name ]) ) { | |
$out[ $name ] = $a[ $name ]; | |
} else { | |
$out[ $name ] = $default; | |
} | |
} | |
return $out; | |
} | |
$defaults = [ | |
'a'=>'apple', | |
'b'=>'banana', | |
'c'=>'carrot', | |
]; | |
$options = [ | |
'a'=>null, | |
'b'=>'bowling ball', | |
'c'=>'cucumber' | |
]; | |
// array_merge is not enough | |
$m1 = array_merge( $options, $defaults ); | |
// this way works, but is weird to read, and moves keys around | |
$m2 = array_filter($options) + array_filter($defaults); | |
// this way works, and is readable | |
$m3 = my_merge( $options, $defaults ); | |
var_dump($m1); | |
var_dump($m2); | |
var_dump($m3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment