Adding multiple taxonomy terms to a single node programmatically I have the following iteration:

  foreach($category as $cat) {
              insert_term_if_not_exists($cat, 'tags');
              $term_tags = taxonomy_get_term_by_name($cat);
              $tid_tags = key($term_tags);
              $lang_tags = field_language('node', $node, 'field_tags');
              $node-&gt;field_tags[$lang_tags][0]['tid'] = $tid_tags;
            }
          }
       }
  node_save($node);


which relies on the following function to create non-existent taxonomy terms:

function insert_term_if_not_exists($term_name, $vocabulary_name) { 
  $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary-&gt;machine_name);
    if(empty($matched_terms)) {
      $term = new stdClass();
      $term-&gt;vid = $vocabulary-&gt;vid;
      $term-&gt;name = $term_name;
      taxonomy_term_save($term);
    } else {
      $term = array_shift($matched_terms);
    }
return $term;
}


This couple pieces of code work great to create new taxonomy terms (taken from $category array) and to associate a node with the last taxonomy term. And I need to add all of the taxonomy terms which went through iteration above to the node. 

Looking everywhere to find proper instructions to add multiple taxonomy terms to a single node programmatically without much success. Hope someone here can point me to the right direction, thanks!
Finally I have a working code:

insert_term_if_not_exists($cat, 'tags');
              $term_tags = taxonomy_get_term_by_name($cat);
              $tid_tags = key($term_tags);
              array_push($tids, $tid_tags);
              $lang_tags = field_language('node', $node, 'field_tags');
            }
          }
          foreach ($tids as $index =&gt; $tid) { $node-&gt;field_tags[$lang_tags][$index]['tid'] = $tid; }

       }


All the credit goes to user Albright in IRC channel #drupal at http://webchat.freenode.net who pointed out to me that I needed to collect the tids in an array, then add a second loop which loops through that array and adds the tids one at a time to field_tags.