Hi I have a method that returns an array of support tickets. Each support ticket can have many notes so I have a method that returns an array of tickets notes with that ticket id. I want to display the notes alongside the ticket which would mean nesting the get notes inside the foreach loop.
foreach($tickets as $ticket){
//display ticket info
//now get ticket notes using method getNotes()
foreach($ticketnote as $note){
//display note
}
}
Do nested loops like this have performance implications? Is this good practice?
It’s not a problem.
Nested loops have no specific performance implications.
But of course, a lot of data may be processed; depending on how much it is, you could reach memory or performance limits. But that is a given, and would also occur if you would use a different control structure instead of a nested loop.
An array-/foreach()-based solution will always require loading the full data set into memory before it starts processing.
If you are fetching data from a database, you could consider re-structuring your functions so they fetch and process a database record one by one instead of loading them all into an array, and
foreaching over them. That allows you to process data sets that are larger than your script’s memory limit.