cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
Anonymous
Not applicable

Performing a FOR loop in PowerApps

Until FOR loops are added in PowerApps, I have a workaround that I've been using and it's really come in handy.

I start by adding a collection in my App's OnStart property (I'll show at the end how to do this in Flow, which I prefer).

I've attached a template for this from 0-1000 (For.txt at the bottom)

 

ClearCollect(Loop,
{Index:0},
{Index:1},
{Index:2},
{Index:3},
...
{Index:100}
)

 

 You can now perform a FOR loop by filtering this collection. For example, if I want to get a collection of dates that are 7 days from a selected date, I can do this:

 

Clear(NextDates);
ForAll(Filter(Loop,Index<=7),
Collect(NextDates,
 {
     Date:DateAdd(DatePicker1.SelectedDate,Index,Days),
     DaysSincePickedDate:Index,
     DayOfWeek:Weekday(DateAdd(DatePicker1.SelectedDate,Index,Days))
}
))

 

I get this result:
2020-01-14 08_52_38-Window.png\

Remember that the numbers don't have to be hardcoded. You can use CountRows(),a numeric input, or any other integer to drive this code.

The shell of the FOR loop looks like this:

 

Set(i,0);
ForAll(
Filter(Loop,Index<=7,Index>=i),
//Code
)

 

This would be the equivalent to something like this:

 

for (i = 0; i <= 7; i++)
{
 //code
}

 

To clean up the Loop collection, I use Flow. Here's what that solution looks like:

for.png

I can now use this code to get my Loop collection (I like to rename the column to Index, since Value is the generic term from Flow)

 

ClearCollect(Loop,RenameColumns(For.Run(1000),"Value","Index"));

 

That will return a collection of 1000 rows without all the manual coding! This Flow is pretty slow, so you can also setup this logic to only load it once for each user (this saves the collection to memory on mobile):

 

LoadData(Loop,"Loop", true );
If(CountRows(Loop)=0,
  ClearCollect(Loop,RenameColumns(For.Run(100),"Value","Index"));
  SaveData(Loop,"Loop")
  )

 

2 ACCEPTED SOLUTIONS

Accepted Solutions
Anonymous
Not applicable

CarlosFigueira
Power Apps
Power Apps

[Updated on 2022-11-03] This is an old reply but I see that it's still getting views, so I decided to update it with the Sequence function, which was added over a year ago (not sure exactly when) which can make it much easier (no need to define large collections):

ForAll(
    RenameColumns(Sequence(CountRows(MyColl)), "Value", "Index"),
    // Code
)

 

[Original reply]

This is a pretty good workaround to the lack of a 'for' construct in PowerApps. I've been using something similar, and those are some things that you can do to make your code a little faster and/or smaller:

  • To create the 'Loop' collection, you can use the abbreviated array syntax ([...]), and rename the column to 'Index':
    • ClearCollect(LoopMaster(RenameColumns([0,1,2,3,4,5,6,7,8,9,...,999],"Value","Index"))
      • Attached a file with the expression to create that loop master
    • This is pretty fast; I have apps with collections like this created with 5000 items, no noticeable performance impact (I even measured in a few apps, and the time it takes is usually around 10-20ms
  • Once you have this (large) loop master collection, you can use the FirstN function to create a loop collection of the size that you want. For example, if you want to loop over a collection MyColl, you can use this expression:

 

 

ForAll(
    FirstN(LoopMaster, CountRows(MyColl)),
    // Code
)

 

 

  • If you don't want to have a very large expression, you can trade off code length by performance. The expression below is equivalent to the one above, but in my tests it takes ~1-5 seconds to execute:

 

 

ClearCollect(LoopMaster,{Index:0}); Clear(LoopMaster);
ForAll(
    RenameColumns([0,1,2,3,4,5,6,7,8,9], "Value", "Hundreds"),
    ForAll(
        RenameColumns([0,1,2,3,4,5,6,7,8,9], "Value", "Tens"),
        ForAll(
            RenameColumns([0,1,2,3,4,5,6,7,8,9], "Value", "Ones"),
            Collect(LoopMaster, {Index: Hundreds * 100 + Tens * 10 + Ones}))))

 

 

  • If you want to create your own loop, using the FirstN function will probably be faster than filtering - especially if your 'master loop' is a large expression. For example, this is equivalent to your example:

 

 

Clear(NextDates);
ForAll(
    FirstN(LoopMaster, 8),
    Collect(
        NextDates,
        {
            Date:DateAdd(DatePicker1.SelectedDate,Index,Days),
            DaysSincePickedDate:Index,
            DayOfWeek:Weekday(DateAdd(DatePicker1.SelectedDate,Index,Days))
        }))

 

 

  • One more performance hint: if you're using ForAll to add elements to an empty collection using the index, you may want to look into using ClearCollect and the AddColumns function to add the elements, followed by the RemoveColumns to remove the index (if you want to do so). In my empirical testing I've found that this is 5-10 times faster than using ForAll (ForAll is not a very performant function). The example above would look like this:

 

 

ClearCollect(
    NextDates,
    DropColumns(
        AddColumns(
            FirstN(LoopMaster, 8),
            "Date", DateAdd(DatePicker1.SelectedDate,Index,Days),
            "DaysSincePickedDate", Index,
            "DayOfWeek", Weekday(DateAdd(DatePicker1.SelectedDate,Index,Days))),
        "Index"))

 

 

 

Hope this helps, and thank you for sharing your ideas!

View solution in original post

19 REPLIES 19
Anonymous
Not applicable

Marking solution
CarlosFigueira
Power Apps
Power Apps

[Updated on 2022-11-03] This is an old reply but I see that it's still getting views, so I decided to update it with the Sequence function, which was added over a year ago (not sure exactly when) which can make it much easier (no need to define large collections):

ForAll(
    RenameColumns(Sequence(CountRows(MyColl)), "Value", "Index"),
    // Code
)

 

[Original reply]

This is a pretty good workaround to the lack of a 'for' construct in PowerApps. I've been using something similar, and those are some things that you can do to make your code a little faster and/or smaller:

  • To create the 'Loop' collection, you can use the abbreviated array syntax ([...]), and rename the column to 'Index':
    • ClearCollect(LoopMaster(RenameColumns([0,1,2,3,4,5,6,7,8,9,...,999],"Value","Index"))
      • Attached a file with the expression to create that loop master
    • This is pretty fast; I have apps with collections like this created with 5000 items, no noticeable performance impact (I even measured in a few apps, and the time it takes is usually around 10-20ms
  • Once you have this (large) loop master collection, you can use the FirstN function to create a loop collection of the size that you want. For example, if you want to loop over a collection MyColl, you can use this expression:

 

 

ForAll(
    FirstN(LoopMaster, CountRows(MyColl)),
    // Code
)

 

 

  • If you don't want to have a very large expression, you can trade off code length by performance. The expression below is equivalent to the one above, but in my tests it takes ~1-5 seconds to execute:

 

 

ClearCollect(LoopMaster,{Index:0}); Clear(LoopMaster);
ForAll(
    RenameColumns([0,1,2,3,4,5,6,7,8,9], "Value", "Hundreds"),
    ForAll(
        RenameColumns([0,1,2,3,4,5,6,7,8,9], "Value", "Tens"),
        ForAll(
            RenameColumns([0,1,2,3,4,5,6,7,8,9], "Value", "Ones"),
            Collect(LoopMaster, {Index: Hundreds * 100 + Tens * 10 + Ones}))))

 

 

  • If you want to create your own loop, using the FirstN function will probably be faster than filtering - especially if your 'master loop' is a large expression. For example, this is equivalent to your example:

 

 

Clear(NextDates);
ForAll(
    FirstN(LoopMaster, 8),
    Collect(
        NextDates,
        {
            Date:DateAdd(DatePicker1.SelectedDate,Index,Days),
            DaysSincePickedDate:Index,
            DayOfWeek:Weekday(DateAdd(DatePicker1.SelectedDate,Index,Days))
        }))

 

 

  • One more performance hint: if you're using ForAll to add elements to an empty collection using the index, you may want to look into using ClearCollect and the AddColumns function to add the elements, followed by the RemoveColumns to remove the index (if you want to do so). In my empirical testing I've found that this is 5-10 times faster than using ForAll (ForAll is not a very performant function). The example above would look like this:

 

 

ClearCollect(
    NextDates,
    DropColumns(
        AddColumns(
            FirstN(LoopMaster, 8),
            "Date", DateAdd(DatePicker1.SelectedDate,Index,Days),
            "DaysSincePickedDate", Index,
            "DayOfWeek", Weekday(DateAdd(DatePicker1.SelectedDate,Index,Days))),
        "Index"))

 

 

 

Hope this helps, and thank you for sharing your ideas!

Anonymous
Not applicable

That's an awesome piece of syntax I didn't know about! I also didn't even think to use FirstN().
Thank you for sharing!

Hey @CarlosFigueira,

 

this is such a useful tip, but I can't for the life of me get the RenameColumns([0,1,2,3,4,5,6,7,8,9,...,999] to work.  I always get a squiggle under the ...  "invalid use of '.'"

 

Is there some preview feature I need to turn on to get this?

 

Thanks

Craig

Anonymous
Not applicable

The '...' is just to denote numbers between 9 and 999, it's not actually part of the formula.

Seriously?  So you have to type in all 1000 numbers? (or script out somewhere else and paste in)

 

There has to be a better way!

 

Anonymous
Not applicable

There are a handful of other ways, but typing it out is the fastest (to process, that is). You could setup an excel document with maxed out rows of consecutive integers and use that, which would probably be the most efficient.

Anonymous
Not applicable

You don't need 1000 "numbers" you need 1000 rows. It can be anything. I just did this:

 

Collect(aLongTable, [" ", " ", " ", " ",

Then copy and pasted:

" ", " ", " ", " ",

to get

Collect(aLongTable, [" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ",

Then copy and paste 

" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ",

etc...

 

 

Took me about 30 seconds to make a table of 1000's of rows. Now you can use this to run your ForAll on your FirstN(aLongTable, NumberOfLoopsYouWant)

 

It's not exactly elegant and I still don't know a great way to increment a variable inside a ForAll but I'm sure there's a workaround for that too.

 

Yeah, I get that, but still, YUCK!

 

The value of putting numbers in the rows is that you can then compare and use partial ranges to get subsets of values - smaller numbers of items.

Helpful resources

Announcements

Celebrating the May Super User of the Month: Laurens Martens

  @LaurensM  is an exceptional contributor to the Power Platform Community. Super Users like Laurens inspire others through their example, encouragement, and active participation. We are excited to celebrated Laurens as our Super User of the Month for May 2024.   Consistent Engagement:  He consistently engages with the community by answering forum questions, sharing insights, and providing solutions. Laurens dedication helps other users find answers and overcome challenges.   Community Expertise: As a Super User, Laurens plays a crucial role in maintaining a knowledge sharing environment. Always ensuring a positive experience for everyone.   Leadership: He shares valuable insights on community growth, engagement, and future trends. Their contributions help shape the Power Platform Community.   Congratulations, Laurens Martens, for your outstanding work! Keep inspiring others and making a difference in the community!   Keep up the fantastic work!        

Check out the Copilot Studio Cookbook today!

We are excited to announce our new Copilot Cookbook Gallery in the Copilot Studio Community. We can't wait for you to share your expertise and your experience!    Join us for an amazing opportunity where you'll be one of the first to contribute to the Copilot Cookbook—your ultimate guide to mastering Microsoft Copilot. Whether you're seeking inspiration or grappling with a challenge while crafting apps, you probably already know that Copilot Cookbook is your reliable assistant, offering a wealth of tips and tricks at your fingertips--and we want you to add your expertise. What can you "cook" up?   Click this link to get started: https://aka.ms/CS_Copilot_Cookbook_Gallery   Don't miss out on this exclusive opportunity to be one of the first in the Community to share your app creation journey with Copilot. We'll be announcing a Cookbook Challenge very soon and want to make sure you one of the first "cooks" in the kitchen.   Don't miss your moment--start submitting in the Copilot Cookbook Gallery today!     Thank you,  Engagement Team

Announcing Power Apps Copilot Cookbook Gallery

We are excited to share that the all-new Copilot Cookbook Gallery for Power Apps is now available in the Power Apps Community, full of tips and tricks on how to best use Microsoft Copilot as you develop and create in Power Apps. The new Copilot Cookbook is your go-to resource when you need inspiration--or when you're stuck--and aren't sure how to best partner with Copilot while creating apps.   Whether you're looking for the best prompts or just want to know about responsible AI use, visit Copilot Cookbook for regular updates you can rely on--while also serving up some of your greatest tips and tricks for the Community. Check Out the new Copilot Cookbook for Power Apps today: Copilot Cookbook - Power Platform Community.  We can't wait to see what you "cook" up!      

Tuesday Tip | How to Report Spam in Our Community

It's time for another TUESDAY TIPS, your weekly connection with the most insightful tips and tricks that empower both newcomers and veterans in the Power Platform Community! Every Tuesday, we bring you a curated selection of the finest advice, distilled from the resources and tools in the Community. Whether you’re a seasoned member or just getting started, Tuesday Tips are the perfect compass guiding you across the dynamic landscape of the Power Platform Community.   As our community family expands each week, we revisit our essential tools, tips, and tricks to ensure you’re well-versed in the community’s pulse. Keep an eye on the News & Announcements for your weekly Tuesday Tips—you never know what you may learn!   Today's Tip: How to Report Spam in Our Community We strive to maintain a professional and helpful community, and part of that effort involves keeping our platform free of spam. If you encounter a post that you believe is spam, please follow these steps to report it: Locate the Post: Find the post in question within the community.Kebab Menu: Click on the "Kebab" menu | 3 Dots, on the top right of the post.Report Inappropriate Content: Select "Report Inappropriate Content" from the menu.Submit Report: Fill out any necessary details on the form and submit your report.   Our community team will review the report and take appropriate action to ensure our community remains a valuable resource for everyone.   Thank you for helping us keep the community clean and useful!

Community Roundup: A Look Back at Our Last 10 Tuesday Tips

As we continue to grow and learn together, it's important to reflect on the valuable insights we've shared. For today's #TuesdayTip, we're excited to take a moment to look back at the last 10 tips we've shared in case you missed any or want to revisit them. Thanks for your incredible support for this series--we're so glad it was able to help so many of you navigate your community experience!   Getting Started in the Community An overview of everything you need to know about navigating the community on one page!  Community Links: ○ Power Apps ○ Power Automate  ○ Power Pages  ○ Copilot Studio    Community Ranks and YOU Have you ever wondered how your fellow community members ascend the ranks within our community? We explain everything about ranks and how to achieve points so you can climb up in the rankings! Community Links: ○ Power Apps ○ Power Automate  ○ Power Pages  ○ Copilot Studio    Powering Up Your Community Profile Your Community User Profile is how the Community knows you--so it's essential that it works the way you need it to! From changing your username to updating contact information, this Knowledge Base Article is your best resource for powering up your profile. Community Links: ○ Power Apps ○ Power Automate  ○ Power Pages  ○ Copilot Studio    Community Blogs--A Great Place to Start There's so much you'll discover in the Community Blogs, and we hope you'll check them out today!  Community Links: ○ Power Apps ○ Power Automate  ○ Power Pages  ○ Copilot Studio    Unlocking Community Achievements and Earning Badges Across the Communities, you'll see badges on users profile that recognize and reward their engagement and contributions. Check out some details on Community badges--and find out more in the detailed link at the end of the article! Community Links: ○ Power Apps  ○ Power Automate  ○ Power Pages  ○ Copilot Studio    Blogging in the Community Interested in blogging? Everything you need to know on writing blogs in our four communities! Get started blogging across the Power Platform communities today! Community Links: ○ Power Apps  ○ Power Automate  ○ Power Pages  ○ Copilot Studio   Subscriptions & Notifications We don't want you to miss a thing in the community! Read all about how to subscribe to sections of our forums and how to setup your notifications! Community Links: ○ Power Apps  ○ Power Automate  ○ Power Pages  ○ Copilot Studio   Getting Started with Private Messages & Macros Do you want to enhance your communication in the Community and streamline your interactions? One of the best ways to do this is to ensure you are using Private Messaging--and the ever-handy macros that are available to you as a Community member! Community Links: ○ Power Apps  ○ Power Automate  ○ Power Pages  ○ Copilot Studio   Community User Groups Learn everything about being part of, starting, or leading a User Group in the Power Platform Community. Community Links: ○ Power Apps  ○ Power Automate  ○ Power Pages  ○ Copilot Studio   Update Your Community Profile Today! Keep your community profile up to date which is essential for staying connected and engaged with the community. Community Links: ○ Power Apps  ○ Power Automate  ○ Power Pages  ○ Copilot Studio   Thank you for being an integral part of our journey.   Here's to many more Tuesday Tips as we pave the way for a brighter, more connected future! As always, watch the News & Announcements for the next set of tips, coming soon!

Hear what's next for the Power Up Program

Hear from Principal Program Manager, Dimpi Gandhi, to discover the latest enhancements to the Microsoft #PowerUpProgram, including a new accelerated video-based curriculum crafted with the expertise of Microsoft MVPs, Rory Neary and Charlie Phipps-Bennett. If you’d like to hear what’s coming next, click the link below to sign up today! https://aka.ms/PowerUp  

Top Solution Authors
Top Kudoed Authors
Users online (4,859)