Welcome Guest, Not a member yet? Register   Sign In
Pre- or appending arrays and preserving key => value pairs
#1

[eluser]GrahamDj28[/eluser]
Hi,

Maybe somebody has already posted something like this, but i could not really find a solution for this.
So I made my own function and would like to share it with all of you!

We all know the array_merge and array_merge_recursive for merging arrays. They both work fine. What i was looking for was a function for prepending or appending values onto an existing array while preserving key => value pairs. When using string keys array_unshift is no problem. But I often have id => title pairs for using in a form select. And then you can't use array_unshift for prepending extra data onto it.

My solution
Code:
/**
  * Merge array's while preserving key => value pairs
  *
  * <p>
  * If prepend is true, the source will be added to the append array
  * If prepend is false, the append will be added to the source array
  * </p>
  *
  * @param array $append, values that must be added
  * @param array $source, the source array
  * @param boolean $prepend
  */
function merge_array($append, $source, $prepend = TRUE) {
  if($prepend) {
   foreach($source as $key => $value) {
    $append[$key] = $value;
   }
  
   return $append;
  } else {
   foreach($append as $key => $value) {
    $source[$key] = $value;
   }
  
   return $source;
  }
}

As you can see there is no check if a key already exists, as I only use this function to prepend an empty select option
(''=>Please make a choise) for a required form select

Hope this can help somebody




Theme © iAndrew 2016 - Forum software by © MyBB