条件によって、連想配列のデータに共通部分、異なる部分があるとき。
以下の場合、Key1からKey4が共通で、$fooがtrueの時のみKey5,Key6も含めたい。
if ( $foo == true) { $array = [ 'Key11' => 'Value1' , 'Key12' => 'Value2' , 'Key13' => 'Value3' , 'Key14' => 'Value4' , 'Key15' => 'Value5' , 'Key16' => 'Value6' , ]; } else { $array = [ 'Key11' => 'Value1' , 'Key12' => 'Value2' , 'Key13' => 'Value3' , 'Key14' => 'Value4' , ]; } |
そのとき、以下のように書いてしまうと、上書きされてしまう。
if ( $foo == true) { $array = [ 'Key15' => 'Value5' , 'Key16' => 'Value6' , ]; } $array = [ 'Key11' => 'Value1' , 'Key12' => 'Value2' , 'Key13' => 'Value3' , 'Key14' => 'Value4' , ]; // $arrayのvar_dump出力結果 // array(4) { // ["Key11"]=> // string(6) "Value1" // ["Key12"]=> // string(6) "Value2" // ["Key13"]=> // string(6) "Value3" // ["Key14"]=> // string(6) "Value4" // } |
そこで、array_merge関数を使ってマージを行うことにより、上書きしないで追記ができる。
バージョン:5.6.28で確認。
if ( $foo == true) { $array = [ 'Key15' => 'Value5' , 'Key16' => 'Value6' , ]; } $array = array_merge ( $array , [ 'Key11' => 'Value1' , 'Key12' => 'Value2' , 'Key13' => 'Value3' , 'Key14' => 'Value4' , ]); // $arrayのvar_dump出力結果 // array(6) { // ["Key15"]=> // string(6) "Value5" // ["Key16"]=> // string(6) "Value6" // ["Key11"]=> // string(6) "Value1" // ["Key12"]=> // string(6) "Value2" // ["Key13"]=> // string(6) "Value3" // ["Key14"]=> // string(6) "Value4" // } |
コメント