Loop in a loop

I have

foreach(range(1,$row['group1_receptacles'] + $row['group2_receptacles'] + $row['group3_receptacles']) as $x)
{
  echo "<li>";
  echo '<div class="alert alert-primary border border-primary" role="alert">';
  echo '<nav aria-label="breadcrumb">';
  echo '<ol class="breadcrumb justify-content-center m-0">';
	foreach($power_trails AS $power_trail) {
		if($power_strip_id == $power_trail['power_strip_id']) { 
		  echo '<li class="breadcrumb-item">';
		  echo '<a href="../power_strips/show_power_strip.php?id='.$power_trail['power_strip_id'].'">';
		  echo '<img src="../../images/power_strip_icon.png" alt="Power" width="30">';
		  echo '</a>';		  
		  echo '</li>';		  
		}
	}
  echo '</ol>';
  echo '</nav>';
  echo '</div>';
  echo "</li>";
}	
 

the result…


The fijrst foreach loops 10 times (tfhags right)
But I have 3 power trails with a power_strip_id of 4,
so why is the picture showing up in all and not 4?

Because for each iteration of the outer loop, you are running through all power trails of the inner loop and so it is hitting 4 each time of the outer loop.

Where does $power_strip_id get defined? Should it be in your foreach() instead of $x?

1 Like

Feels like an awful lot of unnecessary looping.
For each of the 10 receptacles, you’re looping the entire set of power trails.

Why not instead loop the power trails once, before this foreach, and come up with a number of power trails for a given strip, and them simply for 1 to that number, repeat the breadcrumb item? Much less looping.

Consider if you had 100 power trails;
In your current system, you loop 1000 times (10 recepticles * 100 trails).
If you did it up front, you would loop 200 times (once through the set, and then once for each actual placement).

1 Like