Limit foreach loop to 3

I would like to limit this foreach loop to just 3 and hide the rest using PHP. I have done this using javascript, the only issue with this is if there is 20 articles it would be better to not load these in the first place from a performance perspective. In addition, is there a way I can remove the page it is currently on from this look, as it is also one of the projects?

<?php foreach ($page->parent()->children() as $project): ?>
    <h3 class="related">
	 <?= $project->Pagetitle() ?>
    </h3>
<?php endforeach?>

$page->parent()->children() returns a Pages Collection, and Kirby provides an array of methods to further manipulate that collection.

To only display three items from the collection, you can use $page->parent()->children()->limit(3) see https://getkirby.com/docs/reference/objects/pages/limit

To exclude the current one, use $page->parent()->children()->not($currentid)->limit(3) whereas $currentid would have to be the ID of the current page (i.e.$page->id()); see https://getkirby.com/docs/reference/objects/pages/not

1 Like

Also you can use siblings(bool $self = true) method simply:

$page->siblings(false)->limit(3);
1 Like

@ahmetbora & @sebastiangreger Thank you, I am impressed. Kirby is really powerful and easy to understand, furthermore, this forum is very helpful with a fast response…

1 Like

What is missing from the documentation so you could not find it there? Because the limit() function is definitely documented…

In general it seems to me that you either cannot find stuff in the documentation or it is just quicker to ask here, would be really interested in what your problem is with the docs.

Hi, I would say that the documentation is useful of course, but I would suggest the forum is a more direct resource with regards to acquiring answers. The documentation is very large and does not really give specific answers which are contained in large documents, and this can get very confusing. For an advanced programmer, I would say that the documentation is perfect, but for intermediate and novice developers things need to be explained more simply. As Kirby is for all skill levels of website creators I would say that both methods are important in encouraging great websites to be made with this CMS. For example; saying ‘please check the documentation’ would not be helpful for somebody who is using Kirby for the first time. Whereas if they were to search an error that they have found in the forum, this could supply them with a specific answer to how to solve there issue, potentially with a code snippet they can refer to. We are not all experts, some of us are still learning.

1 Like