PHP Function: array_merge_assoc

Relates to PHP

Doing lots of PHP coding at the moment to upgrade my code base for a server migration. One routine I regularly run into is merging data from one array into a map of predefined indexes. For example when POST data is submitted by a form a will fill a map with this data using predefined indexes to ensure no unexpected keys are passed in to exploit the application. The normal approach to this being a foreach loop through the POST data filling in keys that exist as I go. In streamlining my code to use PHP's inbuilt functions I decided to simplify this to a couple of calls to the array function library as follows:


function array_merge_assoc($map, $data) {
  $data_clean = array_intersect_key($data, $map);
  return array_merge($map, $data_clean);
}

The first call to array_intersect_key strips any invalid keys from the $data array hence making it safe to then merge the two arrays in the second function call.

Posted on Tuesday, Oct 30, 2007 at 12:07:06.

Breadcrumbs Trail

[ Home ] -> TW Blog -> Oct 07 -> PHP Function: array_merge_assoc
Site Map

The Severn Solutions website achieves the following standards:

[ XHTML 1.0 ] [ CSS 2 ] [ WAI AA ] [ Bobby AA ]

Page compiled in 0.004 seconds