Advertisements
Home > PHP > Flexible array merge

Flexible array merge

Anyone who works much with php spends a lot of time working with arrays. Most data sources return their results as arrays. Most template systems build tables and other elements from arrays. One of the most common warnings in logs from a lot of software is the result of foreach or other php functions that expect arrays but are passed empty values, or error objects or something else. I have spent a lot of time fixing other people’s code to squash this log clutter.

Not that long ago I wrote a more flexible array_merge to help make merging arrays easier and less prone to errors. Here’s what it looked like.

function nicer_array_merge_recursive(){
  $arrays = array();
  $args = func_get_args();
  if(empty($args)) return array();
  foreach($args as $key => $value){
    if(is_array($value)) $arrays[] = $value;
  }
  if(count($arrays) == 1) {
    $return = array_pop($arrays);
  }else{
    $return = call_user_func_array('array_merge_recursive', $arrays);
  }
  return $return;
}

This function is basically just a wrapper for array_merge_recursive, but it makes sure that the arguments are arrays, and does something nicer than blow up if they aren’t.

Advertisements
Categories: PHP Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: