How to change string every nth occurance in php

JetPack by Automatic is a free image editing SaaS tool for WordPress users. One of its many features is that you can alter the subdomain of the image url being returned to enhance parallel loading of multiple srcs. The three domain options are: “i0”, “i1” and “i2”.

If each photo appears in a foreach statement how can I rotate between the three subdomains so that img1 & img4 use “io”, img2 & img5 use “i1” and img3 uses “i2”?

foreach ($images as $attachment) {

    // If using Photon select full-size photos
    if ( $use_photon == 'one' )
        print $before_img . '<img src="http://i1.wp.com/'. str_replace('http://', '', $$fullsizeurl ) . $resize_img_to .'">' . $after_img;

    // Else select 'medium' thumbnail
    else
        print $before_img . wp_get_attachment_image( $attachment->ID, 'medium' ) . $after_img;

} // foreach

Related posts

Leave a Reply

1 comment

  1. Use the ‘%’ operator on the index of the image. It is the best way to do it.

    foreach ($images as $i => $attachment) {
    
        $host = 'i' + ($i % 3);
        // If using Photon select full-size photos
        if ( $use_photon == 'one' )
            print $before_img . '<img src="http://'. $host .'.wp.com/'. str_replace('http://', '', $$fullsizeurl ) . $resize_img_to .'">' . $after_img;
    
        // Else select 'medium' thumbnail
        else
            print $before_img . wp_get_attachment_image( $attachment->ID, 'medium' ) . $after_img;
    
    } // foreach