title: Output PHP Variable Value In A Position On The Page That Is In A Different Scope?
body: <p>I have a page design where a posts grid is in the second section of the page. There is a simple counter stored by reference in the <code>$count_images</code> variable.</p>
  <p>On the page design, the loop that outputs the posts is below where the count total is going to be displayed (a simplified example given below).</p>
  <p>Is there a way of outputting this higher up the page after the $count_images++ has been implemented?</p>
  <p>I know I can solve this with Javascript by placing the counter value in a hidden element after the while loop and then swapping out the innerText of the <code>&lt;p&gt;</code> tag at the top of the page, but wondered if there was a (preferred) way around this problem in PHP?</p>
  <p>I really apologise if there is a screamingly obvious answer to this, but I'm still relatively new to coding in general and PHP and I can't seem to find any similar examples / questions.</p>
  <pre><code>&lt;p id=&quot;counter&quot;&gt;Number of images by this contributor: &lt;?php // $count_images to be echoed near top of page ?&gt;&lt;/p&gt;
  
  &lt;?php
      $stmt = $connection-&gt;prepare(&quot;SELECT * FROM imageposts WHERE username = :username&quot;);
      $stmt-&gt;bindParam(':username', $username);
      $stmt-&gt;execute();   
  
      $count_images = 0;  // AT THE BEGINNING THERE ARE 0 IMAGES
  
      while ($row = $stmt-&gt;fetch()) {   // LOOP START
  
          $db_image_id = htmlspecialchars($row['image_id']);
          $db_image_title = htmlspecialchars($row['image_title']);
          $db_image_tags = htmlspecialchars($row['image_tags']);
          $db_image_filename = htmlspecialchars($row['filename']);
  
          if ($db_image_filename != NULL  &amp;&amp; $db_image_filename != '') {
              $count_images++;  // IF IMAGE FOUND, INCREASE BY +1
          }
  
  ?&gt;
  &lt;figure&gt;
  
  &lt;!-- html is outputted here including values using the PHP variables above --&gt;
  
  &lt;/figure&gt;
  &lt;?php } // END OF WHILE LOOP ?&gt;
  </code></pre>