函数在If条件下触发

I have a function that triggers from an if statement which checks if a template is valid. At the end I've put an if to check if the aformentioned function has collected any data, if yes it returns TRUE.

When I do an if within the if to see if loop() has returned true it triggers again and I have the information taken two times. How do I prevent this?

I tried using a boolean in global scope that is updated through the if in loop() but I couldn't get it to update.

loop() function:

for ($row = 2; $row <= $highestRow; ++$row) { // START FROM ROW 2 TO AVOID TEMPLATE
    for ($col = 1; $col <= $highestColumnIndex; ++$col) { // START FROM COLUMN A
        $value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
        // SORTING INTO CORRECT ARRAYS
        if ($col == 1){
          $ids[] = $value;
        };
        if ($col == 2){
          $names[] = $value;
        };
        if ($col == 3){
          $ages[] = $value;
        };
    }
  }
  if (!empty($ids) && !empty($names) && !empty($ages)){
    return TRUE;
  };

The if statement:

if ($idTemplate == "ID" && $nameTemplate == "NAME" && $ageTemplate == "AGE"){
  loop();
  if (loop() == TRUE){
    addSQL();
  }
};

I'm expecting loop() not to run two times and to have it confirmed that it's actually working so addSQL() runs