Advertisements

Archive

Posts Tagged ‘php arrays’

Flexible array merge

February 10, 2008 Leave a comment

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: