How to get the count of all unique tags defined in a single tags field?

I am struggling to split the tags field and get the count of the tags of it. How to do that?

My input:
Tags: Foo,Boo,Test,Baa

What I want for output:
Count: 4

This should do it:

<?= $page->tags()->split(',')->count() ?>

If it doesn’t, try pluck() instead, which i think supercedes the older split() and is a little more powerful.

<?php
$tags = $page->tags()->pluck('tags', ',', true); 
$tagcount = $tags->count();
?>

<?= $tagcount ?>

That won’t work, because you can’t call count() on an array nor can you call pluck() on a field.

Use

<?php
echo count(array_unique($page->tags()->split()));
2 Likes

Are you sure? I do this in few projects and the docs describe that you can… and count says it counts an array in the docs…

…confused!

So for example i do this in blog controller to get a list of all the tags on all the pages by picking up the value of the tags field…

  // fetch the basic set of pages
  $posts = $site->index()->find('blog')->children()->unscheduled()->flip()->visible();
  if($tag = param('tag')) {
    $posts = $posts->filterBy('tags', $tag, ',');
  }
  // fetch all tags
  $tags = $posts->pluck('tags', ',', true);
  asort($tags);

Surely i can chain count onto $tags since its an array? Am i missing something?

Yes, I am very sure. pluck() is a method of the collection class. So it goes through a collection and plucks all values of a given field within that collection and returns an array of these tags.

In your example above, $posts is such a pages collection, so you can use the pluck() method.

@andalusi, however, wants to count the tags of a single field of a single page, not of a collection.

Here you are trying to use the pluck() method on a single tags field, which is a field object, not a collection and therefore won’t work.

<?= $page->tags()->split(’,’)

This code returns an array. So you cannot chain count() onto it, because the count() method is also a method of the collection class.

No, because count()(like pluck()) is a method of the collection class. So you could do this, i.e. create an instance of the collection class from the array and then use count() on this new collection object:

$c = new Collection(array_unique($page->tags()->split()));
dump($c->count());

Check out the documentation, it tells you what the return values of all the methods are.

Thanks @jimbobrjames & @texnixe!
Merry christmas