title: How to merge two arrays and concat the values with PHP
body: <p>I'm looking for an easy solution to create a little function to merge two arrays with value concat (I'm using it to create html tag attribute):</p>
  
  <pre><code>$default["class"] = "red";
  
  $new["class"] = "green";
  $new["style"] = "display:block"
  </code></pre>
  
  <p>The result:</p>
  
  <pre><code>$res["class"] = "red green";
  $res["style"] = "display: block";
  </code></pre>
  
  <p>and one more option: 
  if the <code>$new</code> is not an array, just concat with the <code>$default["class"]</code> (if this exist), and the other side: if the <code>$default</code> is a simple string, convert to array: <code>$default["class"] = $default</code>;</p>
  
  <p>I created a function but would like to use an easier, shorter way for that:</p>
  
  <pre><code>function attrMerge( $default, $new="" ){
      $res = array();
  
      if(!is_array($default)) {
          $res["class"] = $default;
      }
      else {
          $res = $default;
      }
  
      if( $new !== "" ){
          if(!is_array($new)) {
              if(isset($res["class"])){
                  $res["class"].= " ".$new;
              }
          }
          else {
              foreach($new as $key=&gt;$value) {
                  if( isset($res[$key]) ) {
                      $res[$key].= " ".$value;
                  }
                  else {
                      $res[$key] = $value;
                  }
              }
          }
      }
  
      return $res;
  }
  
  $a = attrMerge("red", array("class"=&gt;"green", "style"=&gt;"display: block;"));
  </code></pre>