PHP continuing in code before previous functions finished
<p>I have a full-text search code that either uses faulty logic, or else it defies the way I understand PHP to work. First, I have a rather lengthy function called *file_find* that returns an array. I have an array of files called *all_files* that I step through running *file_find* on each, like this:</p>

<pre><code>$allftsearch_results = array();
 for ($i = 0; $i &lt;= count($all_files); $i++) {
 $current_file = $all_files[$i];
  //Run one file
  if (file_exists($current_file)) {
   $search_result = file_find($current_file, $phpfilenames[$i], $num_ands, $keywords_core, $keywords_boolean, $phpfilenames, $ascii_limit);
  //Add file results to allftsearch_results array
  if (!empty($search_result)) {
   foreach ($search_result as $keyfilename =&gt; $invpagevalue) {
     array_push($allftsearch_results, $keyfilename);
     }
    }
   }
  }
</code></pre>

<p>If I print out $current_file as it's sent to *file_find*, it reflects the order it should: the A's, then the B's, then the C's etc. But when I print out $keyfilename after the results come back, they lag behind the files actually fed to the function. I end up with something like this:</p>

<ul>
<li>Current file: burnham.html</li>
<li>Current file: burroughs.html</li>
<li>Current file: burton.html</li>
<li>Current file: busch.html</li>
<li>Current file: busoni.html</li>
<li>Current file: butler.html</li>
<li><strong>Returned file:</strong> albee</li>
<li>Current file: byrd.html</li>
<li>Current file: byrnes.html</li>
<li>Current file: byron.html</li>
<li><strong>Returned file:</strong> albeville
etc.</li>
</ul>

<p>It's all within the same if file_exists statement, so the code shouldn't even get to the if foreach ($search_result ...) until the *file_find* has finished. But apparently it's running in the background and returning results after several other files have been sent to it and stack up. This wouldn't be a problem if I was printing all the results out at once, but I have AJAX sending batches of 100 files at a time, and it's returning results all out of order, with A's coming in after B's and results being repeated when they shouldn't.</p>

<p>How can I make sure it waits to proceed with the code until the *file_find* is finished?</p>
