How to begin indexOf() from 1 not 0?

I have a structure and I am looking for a way to number each structure field that is looped through on the front-end without having to create a number field and manually number each one

I’m currently using:

`    <p><?= $categories->indexOf($categorie) ?></p>`

The issue is it begins at 0 and I want to find a way to begin index from 1

Add 1.

 <p><?= $categories->indexOf($categorie) + 1 ?></p>
2 Likes

I hope it’s okay to ask this further question…
I want to add a 0 in front on the index number if it is less than 10 but can’t work it out

<?php foreach($categories as $categorie):?>
    <p><?php if($categories->length() < 10): ?>0<?php endif ?><?= $categories->indexOf($categorie) + 1 ?></p>
<?php endforeach ?>

length() is not a method of a structure collection, use count()- the reference is your friend if you are not sure what methods you can use.

1 Like

Sorry I’m still quite new and don’t know what to search for sometimes - thanks for your help!

The issue with this that it is adding a 0 to each category field but if the count is more than 10 it doesn’t add a 0 to any of the category fields

Could you please provide more context?

What is the first column? What is the second? What does the blueprint look like?

The first column is an example of there being less than 10 category items and the second has 10

<?php $menuitems = $page->menuitems()->toStructure(); ?>
<?php foreach($menuitems as $menuitem):?>

    <div class="span-6">
    <h3><?= $menuitem->header()->kt() ?></h3>
    <?php $categories = $menuitem->categories()->toStructure(); ?>
    <?php foreach($categories as $categorie):?>
        <div class="flex-r flex-s-between">
        <?= $categorie->item()->kt() ?>
        <p><?php if($categories->count() < 10): ?>0<?php endif ?><?= $categories->indexOf($categorie) + 1 ?></p>
        </div>
    <?php endforeach ?>
    </div>
<?php endforeach ?>

blueprint:

    tabs:
      content:
        label: Content
        icon: text
        fields: 
          menuitems:
            type: structure
            fields:
              header:
                type: text
                width: 1/3
                label: Category Title
              categories:
                type: structure
                label: Menu Items
                width: 2/3
                fields:
                  item:
                    type: text
                    buttons: false
                    width: 1/2

The problem is that you are counting the wrong stuff. In reality you have to check if the index number is below 9/10 not the number of category items.

1 Like

Thank you so much!

This was the solution:
<?php if($categories->indexOf($categorie) < 9): ?>0<?php endif ?><?= $categories->indexOf($categorie) + 1 ?>