AnonProg
AnonProg

Reputation: 117

How to retrieve specific values from array with multiple PHP for loops?

I have been working on trying to retrieve specific results from a PHP for loop without success.

My objective is to run a loop on an array and to pull the specific value each time if it exists within the array. I am able to run the first loop and retrieve a value, however, when I run the second for function it retrieves the exact same number. I haven't been able to figure out why. E.g. The first loop returns the value of 6, but so does the second loop. I am trying to retrieve 6 if it exists from the first loop and 7 if it exists in the second loop. 7 is located in the array, so it should return 6 in the first for statement and 7 on the second.

Here is what I have done so far:

for ($i = 0; $i < count($final_data); $i++) {
    $check_sector = $final_data[$i]['sector'];
    $check_image = $final_data[$i]['image'];
      if($final_data[$i]['sector'] == 6){
        echo "<div id='6' class='w3-button w3-ripple grid-item-sector' onclick='getSector(this.id)'>"
        . "<div id='ss6' style='position: absolute; width: 100px; height: 100px; background-image: url(" . $check_image . ");'></div>"
                ."<div id='s6' class='overlay' ></div></div>";
        break;
      }else{
        echo "<div id='6' class='w3-button w3-ripple grid-item-sector' onclick='getSector(this.id)'>"
        ."<div id='s6' class='overlay' ></div></div>";
        break;
      }
  }

  for ($i = 0; $i < count($final_data); $i++) {
    $check_sector = $final_data[$i]['sector'];
    $check_image = $final_data[$i]['image'];
      if($final_data[$i]['sector'] == 7){
        echo "<div id='7' class='w3-button w3-ripple grid-item-sector' onclick='getSector(this.id)'>"
        . "<div id='ss7' style='position: absolute; width: 100px; height: 100px; background-image: url(" . $check_image . ");'></div>"
                ."<div id='s7' class='overlay' ></div></div>";
        break;
      }else{
        echo "<div id='7' class='w3-button w3-ripple grid-item-sector' onclick='getSector(this.id)'>"
        ."<div id='s7' class='overlay' ></div></div>";
          break;
      }
  }

Upvotes: 0

Views: 28

Answers (1)

DanielRead
DanielRead

Reputation: 2794

When you get to the second foreach loop, it’s hitting the first element in the array first.

So it’s saying is 6==7? No, so it goes to the else echo statement.

Then you have a break so it gives up and never checks the second element in the array which is the 7.

Upvotes: 1

Related Questions