1

I'm having a very peculiar issue with Wordpress right now that I can't understand, and hopefully someone here will have experience with it to help solve it.

I'm trying to iterate through the array returned by get_the_tags() using a standard loop (not foreach), but whenever I attempt to access it through index, it doesn't return anything. According to the Wordpress Codex, get_the_tags() returns an array of tag data that is associated with the post.

Weirdly enough, a foreach structure works perfectly fine when dealing with it; however indexing it does not.

Here's what I've tried:

$tags = get_the_tags();
$total = count($tags);
echo($total); // Returns 2

// This one does nothing    
for($i=0; $i<$total; $i++){
   echo($tags[$i]->name); // Does nothing
}

// This one works:
foreach($tags as $tag){
    echo($tag->name); // Prints the tags, as it should
}

So for whatever reason, the above example using the index does not work when it comes to get_the_tags(), but it works fine in a foreach loop. But that's not all that's weird. Using get_tags() to get all tags for the blog in an array in a similar fashion works fine in both situations!

So for example:

$tags = get_tags();
$total = count($tags);
echo($total); // Returns 4

for($i=0; $i<$total; $i++){
   echo($tags[$i]->name); // Prints the 4 tags
}

foreach($tags as $tag){
    echo($tag->name); // Prints the 4 tags
}

They both return arrays of tags according to the Wordpress Codex, so what gives for the top one not working using an index? I'm trying to do something that requires access to the index (and dealing with more than 1 array, so it can't be a foreach).

Would anyone have any ideas on how to fix it (or at least access the data)? Has anyone else experienced this bizarre issue?

3
  • Both versions of the loop work for me.
    – s_ha_dum
    May 6, 2013 at 2:44
  • So get_the_tags() works fine for you? Weird... Any idea what would cause only one to work but not another? I mean, data is clearly there May 6, 2013 at 2:47
  • I think that @MagentaCuda found the difference for you.
    – s_ha_dum
    May 6, 2013 at 4:11

1 Answer 1

1

get_the_tags() returns an array but the indexes do not start at 0 because they are the term ids.

1
  • That's really bizarre, but I guess that would make sense as to why an index of 0-4 wouldn't read it. Why would it be designed so weirdly like that when almost every other array-returning function starts at 0? It just seems to break standard programming principles for it to be different. At any rate, I really appreciate the answer! I wound up going with using wp_get_post_tags($post->ID) in the end, and it worked much better. May 6, 2013 at 20:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.