Small hint array_slice for tags

If you need to get random tag
(for me this is needed for show example search phrases )

You might help this hint

<span class="search-examples">Try to search:
<?php $items = $page->header_search_terms()->split(); ?>
<?php shuffle($items); ?>
<?php $new_items = array_slice($items, 0, 1); ?>
<?php foreach($new_items as $item): ?>
<span><?php echo $item ?></span>
<?php endforeach ?>
</span>

http://take.ms/rurbQ (this is what do you get)

1 Like

I think what you’re trying to do could be achieved in a simpler form:

<span class="search-examples">Try to search:
<span><?php echo a::first($page->header_search_terms()->split()->shuffle()) ?></span>
</span>

You can chain shuffle without passing an argument. It will take the current chained collection as an argument.
You don’t need to do a foreach loop if your aray only contains one item.
a::first is a toolkit function that returns the first element of an array: https://getkirby.com/docs/toolkit/api/a/first

I hope this is helpful for you and others.

That won’t work unfortunately as split() returns an array, not a collection. But the following should work:

<span class="search-examples">Try to search:
<?php $terms = $page->header_search_terms()->split() ?>
<?php shuffle($terms) ?>
<span><?php echo a::first($terms) ?></span>
</span>
2 Likes

And here I am omitting the obvious in my own comment. Indeed, shuffle expects a collection… My bad !

shuffle() does not take any arguments or expect collections, but it is a method of collections (= not a method of arrays).
I’m sure that’s what you meant, just being nitpicky. :wink:

1 Like

Thanks for correcting me. The vocabulary is definitely something that’s in lacking at!