PHP totally random image?

Discussion in 'PHP' started by scottlpool2003, Aug 28, 2012.

  1. #1
    I'm working off this little script here to pull random image ads out.

    The way they work is like so:

    LARGE AD
    -SMALL AD- -SMALL AD-
    LARGE AD
    -SMALL AD- -SMALL AD-

    Large ad works fine with:

    			<?php
    	$images = array(
    	    0 => 'ad_half_1.jpg',
    	    1 => 'ad_half_2.jpg',
    	    
    	);
    	$image = $images[ rand(0,(count($images)-1)) ];
    	$output = "<img src=\"/images/ads/".$image."\" alt=\"\" border=\"0\" />";
    	print($output);
    ?>		
    PHP:
    As there are only 2 images for that large ad.

    I'm struggling with the 2 small ads as sometimes 2 of the same come out. Is there any way to stop the same images outputting?
     
    Solved! View solution.
    scottlpool2003, Aug 28, 2012 IP
  2. #2
    
    <?php
        $small_images = array(
            0 => 'ad_half_1.jpg',
            1 => 'ad_half_2.jpg',
            2 => 'ad_half_3.jpg',
            4 => 'ad_half_4.jpg',
        );
        $key = rand(0,(count($small_images)-1));
        $image = $small_images[ $key ];
        print("<img src=\"/images/ads/".$image."\" alt=\"\" border=\"0\" />");
        unset($small_images[$key]);
    
        $key = rand(0,(count($small_images)-1));
        $image = $small_images[ $key ];
        print("<img src=\"/images/ads/".$image."\" alt=\"\" border=\"0\" />");
        unset($small_images[$key]);
    ?>
    
    PHP:
    There are more elegant ways to do it ... but really all you need to do is unset that image array's key after using it before you generate the second random image.
     
    kbduvall, Aug 28, 2012 IP
  3. scottlpool2003

    scottlpool2003 Well-Known Member

    Messages:
    1,708
    Likes Received:
    49
    Best Answers:
    9
    Trophy Points:
    150
    #3
    Thank you!
     
    scottlpool2003, Aug 29, 2012 IP