title: Iterate through a foreach loop in PHP and replace a counter placeholder with str_replace
body: <p>This is vaguely WordPress related, but it's purely PHP question.</p>
  
  <p>I have a function that gets all the images in a post and the function lets me control what comes before and after the images i.e. <code>&lt;figure&gt;</code> and <code>&lt;/figure&gt;</code>.</p>
  
  <p>I have a function like this:</p>
  
  <pre><code>function get_some_images( $args = "" ) {
      $defaults = array(
          'before_img' =&gt; '&lt;figure&gt;', 
          'after_img'  =&gt; '&lt;/figure&gt;', 
          );
      $args = wp_parse_args( $args, $defaults );
      extract( $args, EXTR_SKIP );
      // $images is an array of images from the curren post
      $i = 1;
      foreach($images as $image) {
          // Pseudocode
          $output .= $before_img . $image . $after_img;
          $i++;
      }
      return $output; 
  }
  </code></pre>
  
  <p>Usage:</p>
  
  <pre><code>$args = array(
      'before_img' =&gt; '&lt;div class="img"&gt;',
      'after_img'  =&gt; '&lt;/div&gt;',
      );
  echo get_some_images($args);
  </code></pre>
  
  <p>All fine so far. But what if I want to add an iteration counter to the <code>before_img</code>, I'm using <code>%d</code> as a placeholder:</p>
  
  <pre><code>$args = array(
      // Here's the difference, note the %d placeholder for iteration count
      'before_img' =&gt; '&lt;div class="img-%d"&gt;',
      'after_img'  =&gt; '&lt;/div&gt;',
      );
  get_some_images($args);
  </code></pre>
  
  <p>I tried something like this:</p>
  
  <pre><code>$i = 1;
  foreach($images as $image) {
      // Here's the tricky bit
      $before_img = str_replace('%d', $i, $before_img);
      $output .= $before_img . $image . $after_img;
      $i++;
  }
  </code></pre>
  
  <p>But it won't iterate the counter, outputs same number for all the iterations:</p>
  
  <pre><code>&lt;div class="img-1"&gt;&lt;img&gt;&lt;/div&gt;
  &lt;div class="img-1"&gt;&lt;img&gt;&lt;/div&gt;
  &lt;div class="img-1"&gt;&lt;img&gt;&lt;/div&gt;
  ...
  </code></pre>
  
  <p>If I echo the <code>$i</code> out, it's iterated normally:</p>
  
  <pre><code>$i = 1;
  foreach($images as $image) {
      echo $i . ', ';
      $i++;
  }
  // Outputs: 1, 2, 3...
  </code></pre>
  
  <p>I tried some nested loops also, but with little luck.</p>
  
  <p><img src="https://i.stack.imgur.com/4k8eH.jpg" alt="enter image description here"></p>