get_the_tags() not iterating through for/while loop, but will with foreach

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.

Read More

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?

Related posts

1 comment

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

Comments are closed.