PHP array_replace without creating keys

前端 未结 5 1625
不思量自难忘°
不思量自难忘° 2021-02-05 11:25

I am trying to overwrite the elements of one array with values from another – without creating additional elements in the process.

For example:

         


        
相关标签:
5条回答
  • 2021-02-05 11:59

    Try this:

    $result = array_replace($base, array_intersect_key($replace, $base));
    
    0 讨论(0)
  • 2021-02-05 12:00

    You can use array_intersect_key and array_merge to do it:

    $result = array_merge($base, array_intersect_key($replace, $base));
    

    array_intersect_key isolates those elements of $replace with keys that already exist in $base (ensuring that new elements will not appear in the result) and array_merge replaces the values in $base with these new values from $replace (while ensuring that keys appearing only in $base will retain their original values).

    See it in action.

    It is interesting to note that the same result can also be reached with the order of the calls reversed:

    $result = array_intersect_key(array_merge($base, $replace), $base);
    

    However this version does slightly more work, so I recommend the first one.

    0 讨论(0)
  • 2021-02-05 12:00

    the following should do it:

    foreach ($replace as $k => $v)
       if (isset($base[$k])) $base[$k]=$v;
    
    0 讨论(0)
  • 2021-02-05 12:09

    I can't think of a built in method for that, however, it would be trivial with a loop and array_key_exists.

    foreach( $replace as $k => $v )
    {
       if ( array_key_exists( $k, $base ) )
          $base[ $k ] = $v;
    }
    
    0 讨论(0)
  • 2021-02-05 12:18
    print_r(array_intersect_key($replace, $base));
    
    0 讨论(0)
提交回复
热议问题