title: While Loop Through An Array
body: <p>Creating a block builder that loops through blocks pulled form database in order.</p>
  
  <pre><code>if( loop_blocks()) {
      while( loop_blocks()) {
          if( have_block('standard-content-block')) {
              echo 'standard-content-block';
          }
  
          elseif( have_block('executive-intro-block')) {
              echo 'executive intro block';
          }
      }
  }
  </code></pre>
  
  <p>My function loop_blocks pulls the blocks from the database in order and set the array as a global variable:</p>
  
  <pre><code>function loop_blocks() {
          global $db;
  
          $page_id = get_page_id();
          $GLOBALS['loop_position'] = 0;
          $loop_position = $GLOBALS['loop_position'];
  
          $stm = $db-&gt;prepare("SELECT * FROM page_blocks WHERE page_id = :id ORDER BY `block_order` ASC");
          $stm-&gt;execute(array(':id' =&gt; $page_id));
          $res = $stm-&gt;fetchAll();
          $GLOBALS['block_loop'] = $res;
          if(!$res) {
              return false;
          } elseif(!$GLOBALS['block_loop'][$loop_position]) {
              return false;
          } else {
              return true;
          }
      }
  </code></pre>
  
  <p>The function have_block gets the current loop position and determines whether the name as determined, exists in the array and increases the loop position:</p>
  
  <pre><code>function have_block($block_name) {
          $loop_position = $GLOBALS['loop_position'];
  
          if(!$GLOBALS['block_loop'][$loop_position]) {
              return false;
          } elseif(!$GLOBALS['block_loop'][$loop_position][block_name] = $block_name) {
              return false;
          } else {
              $GLOBALS['loop_position'] = $loop_position+1;
              return true;
          }
      }
  </code></pre>
  
  <p>This returns an infinite loop however and I can't figure out a way to move the while loop onto the next step?</p>
  
  <p><strong>EDIT</strong> I'm using a while loop because the function have_block will set-up a global variable for the current block id. This will then be used within a function called the_element. Such as:</p>
  
  <pre><code>if( loop_blocks()) {
      while( loop_blocks()) {
          if( have_block('standard-content-block')) {
              the_element('heading');
          }
      }
  }
  </code></pre>
  
  <p>If I don't use the function have_block to set this up, then I'd need to pass the block id from the foreach loop into every element as a second argument.</p>