Forum for discussing general topics related to Couch.
13 posts Page 2 of 2
still no joy, i've changed the count to 4 again and it worked with the above code, however i only want to show the one random image.
Hi Simon,

That is due to a quirky behaviour of the 'array_rand' PHP function we are using - it returns an array if more than 1 random items are selected but returns a simple number if only one item if selected.
Here is the revised PHP code that handles both the scenarios -

Code: Select all
<cms:php>

   $path_to_images = 'uploads/image/fan-images/';
   $count_rand = 1; // Number of random images to pick
   
   // Valid extensions
   $extensions = array( 'jpg','jpeg','gif','png','bmp' );
   
   // Open folder and get files
   $images = array();
   if( $handle = opendir('<cms:show k_admin_path />' . $path_to_images) ){
      while (false !== ($file = readdir($handle))) {
         if( $file != "." && $file != ".." ){
            $ext = strtolower( substr(strrchr($file, "."), 1) );
            if( in_array($ext, $extensions) ){
               $images[] = '<cms:show k_admin_link />' . $path_to_images . $file;
            }
         }
      }
      closedir($handle);
   }
   
   // Select the indicated number of random images
   $count_rand = ( count($images)<$count_rand ) ? count($images) : $count_rand;
   $rand_keys = array_rand( $images, $count_rand );
   if( is_array($rand_keys) ){
      for( $x=0; $x<count($rand_keys); $x++ ){
         //echo '<img src="'.$images[$rand_keys[$x]].'" /><br/>';
         echo '<div class="fans-image-area-1"><img src="'.$images[$rand_keys[$x]].'" width="140" height="90" /></div>';
      }
   }
   else{
      echo '<div class="fans-image-area-1"><img src="'.$images[$rand_keys].'" width="140" height="90" /></div>';
   }

</cms:php>

Hope this helps.
Yep its working :lol: thanks again KK
13 posts Page 2 of 2