Drupal - How to get term Id from name with taxonomy_get_term_by_name

pcrx20 picture pcrx20 · Jul 24, 2013 · Viewed 9.2k times · Source

I have tried to use the following code to get a termId from a term:

  $term = taxonomy_get_term_by_name($address_string); 
  $termId = $term[0]->tid;

There is 1 result, but it is appearing as term[30] - so the above code doesn't work.

I thought I could access the term array by looking at the first element - e.g. $term[0]

What am I doing wrong?

Here is the result of var_dump($term):


array (size=1)
  30 => 
    object(stdClass)[270]
      public 'tid' => string '30' (length=2)
      public 'vid' => string '4' (length=1)
      public 'name' => string 'Thonglor' (length=8)
      public 'description' => string '' (length=0)
      public 'format' => string 'filtered_html' (length=13)
      public 'weight' => string '0' (length=1)
      public 'vocabulary_machine_name' => string 'areas' (length=5)

Many thanks,

PW

Answer

Vladimir Hraban picture Vladimir Hraban · Jul 24, 2013

Probably the best option would be

$termid = key($term);

It will output 30

http://php.net/manual/en/function.key.php

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.

May be better to call

reset($term);

before calling the key function

Reset reset the internal array pointer to the first element

Other option is as Drupal API manual says itself, https://api.drupal.org/comment/18909#comment-18909

/**
 * Helper function to dynamically get the tid from the term_name
 *
 * @param $term_name Term name
 * @param $vocabulary_name Name of the vocabulary to search the term in
 *
 * @return Term id of the found term or else FALSE
 */
function _get_term_from_name($term_name, $vocabulary_name) {
  if ($vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name)) {
    $tree = taxonomy_get_tree($vocabulary->vid);
    foreach ($tree as $term) {
      if ($term->name == $term_name) {
        return $term->tid;
      }
    }
  }
  return FALSE;
}