title: Breaking out of Loop from within Callback Function in PHP
body: <p>For a project I am running a high amount of data throughput and need to chunk it to process it. This process is run several times for different users. All of that is working well. Occasionally though, the processing needs to throw a stop error to break out of the script gracefully (IE: Not using <code>die()</code> but instead log an error) and continue with next user's data.</p>
  
  <p>Here is a very simplified version of my script. I know that this could be rearranged in this simplistic mode to remove the callback function in its entirety, but the actual script requires it to be setup like this.</p>
  
  <pre><code>&lt;?php
  $user_data = array(
      'User 1' =&gt; array(
          array(
              1,2,3,4,5,6,7,8,9,
          ),
          array(
              10,11,12,13,14,15,16,17,18,
          ),
      ),
      'User 2' =&gt; array(
          array(
              1,2,3,4,5,6,7,8,9,10
          ),
          array(
              11,12,13,14,15,16,17,18,19,20
          ),
      ),
  );
  foreach($user_data as $data_chunks){
      foreach($data_chunks as $data_set){
          foreach($data_set as $data){
              myFunction($data, function($returned_data, $stop){
                  if($stop){
                      //log error
                      break 2;
                  }
                  print $returned_data." ";
              });
          }
      }
  }
  
  function myFunction($data, callable $f){
      $stop = false;
      if($data&gt;5){
          $stop = true;
      }
      $data_to_return = $data*2;
      $f($data_to_return,$stop);
  }
  ?&gt;
  </code></pre>
  
  <p>Php throws a fatal error for </p>
  
  <blockquote>
    <p>Fatal error: Cannot break/continue 2 levels</p>
  </blockquote>