Solved

php - display images

Posted on 2012-04-09
12
201 Views
Last Modified: 2012-04-10
hello there,
I have about 30 images in one folder and I would like to display 3 random images but sometimes when displaying randomly I get two images that are the same.. how can I prevent from showing the same image?
0
Comment
Question by:XK8ER
  • 5
  • 3
  • 2
  • +2
12 Comments
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 37826375
can u post your code?
0
 
LVL 1

Author Comment

by:XK8ER
ID: 37826384
it just reads a random image from a path of images..
0
 
LVL 29

Expert Comment

by:Olaf Doschke
ID: 37826554
You create three random numbers in the range of 1 to filecount and if two or all of them are the same generate one or two new numbers until you have three different numbers.

Bye, Olaf.
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 
LVL 1

Author Comment

by:XK8ER
ID: 37826596
this is what I have

<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');
ini_set('display_startup_errors', 'On');

function getRandomFromArray($ar) {
    mt_srand( (double)microtime() * 1000000 );
    $num = array_rand($ar);
    return $ar[$num];
}

function getImagesFromDir($path) {
    $images = array();
    if ( $img_dir = @opendir($path) ) {
        while ( false !== ($img_file = readdir($img_dir)) ) {
            if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
                $images[] = $img_file;
            }
        }
        closedir($img_dir);
    }
    return $images;
}

$root = '';
$path = 'images/andrea/';
$imgList = getImagesFromDir($root . $path);
$img = getRandomFromArray($imgList);

?>

<img src="<?php echo $path . $img ?>" alt="" /> 

Open in new window

0
 
LVL 29

Expert Comment

by:Olaf Doschke
ID: 37826713
And you call this three times, I suppose.

Stop doing that instead let it create three img tags with three unique images this way and call it once only:

<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');
ini_set('display_startup_errors', 'On');

function getRandomArrayElements($ar,$n) {
    mt_srand( (double)microtime() * 1000000 );

    for ($i=1; $i<=n; $i++)
    {
     $num = array_rand($ar);
     $randomelements[] = $ar[$num];
     unset($ar[$num]);
    }

    return $randomelements;
}

function getImagesFromDir($path) {
    $images = array();
    if ( $img_dir = @opendir($path) ) {
        while ( false !== ($img_file = readdir($img_dir)) ) {
            if ( preg_match("/(\.gif|\.jpg|\.png)$/", $img_file) ) {
                $images[] = $img_file;
            }
        }
        closedir($img_dir);
    }
    return $images;
}

$root = '';
$path = 'images/andrea/';
$imgList = getImagesFromDir($root . $path);
$imgRand = getRandomArrayElements($imgList,3);

for each($imgRand as $img)
{?>

<img src="<?php echo $path . $img ?>" alt="" /> 

<?php
}
?>

Open in new window


The image list $imgList is reduced with unset(), while random images are taken from it, so no image is taken twice.

Bye, Olaf.

PS: even simple array_rand() can return $n keys at once. And using array_flip() you can get $n elements at once:

function getRandomArrayElements($ar,$n) {
    mt_srand( (double)microtime() * 1000000 );

    $randomelements = array_rand(array_flip($ar), $n);

    return $randomelements;
}

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 37827023
Input: array.  Output: some number of random selections from the array.  Warning: I have never tested this code, so please be prepared to correct my errors or omissions.

If the array elements are unique, the output will be unique.  If the array elements are not unique but you want them to be unique, you can make the array keys and array values into the same data fields. If you do that, the non-unique array keys will overwrite each other.  See also: http://php.net/manual/en/function.array-unique.php
function getSomeRandomFromArray($arr, $n=3) 
{
    $out = array();
    if (!is_array($arr)) return $out
    shuffle($arr);
    if (count($arr) < $n) return $arr;
    while ($n)
    {
        $out[] = array_pop($arr);
        $n--;
    }
    return $out;
}

Open in new window

0
 
LVL 9

Expert Comment

by:rinfo
ID: 37827077
read all files names in an array  $allFileName
$sel_files = array_rand($allFileName, 3);
$sel_files now should contain 3 distinct filename.
0
 
LVL 9

Expert Comment

by:rinfo
ID: 37827103
You may also use shuffle on $allFileName and
read first three element as random unique filename.
You can be more assured of distinct files names in Shuffle and there could be a chance of
a file name repeated in array_rand.
shuffle($allfilename);
for int $i = 0; $i<3;$i++
   $selFiles = $allfileName[$i];
0
 
LVL 1

Author Comment

by:XK8ER
ID: 37828813
im testing the provide code but its not working and i dont see any errors..
0
 
LVL 9

Expert Comment

by:rinfo
ID: 37829123
can you post the codes you are using
0
 
LVL 9

Expert Comment

by:rinfo
ID: 37829137
can you post the codes you are using
0
 
LVL 9

Accepted Solution

by:
rinfo earned 500 total points
ID: 37829381
These are the codes I have used and worked ok in both the cases
using  array_rand
<?php
  $imageDir = 'FuncIcon';
  $arrAllImages = array();
  $sel_files = array();
  if ($handle = opendir($imageDir)) {    
    while (false !== ($file = readdir($handle))) {
        if(($file == '.') || ($file == '..'))
          {
             continue;
             }
        $arrAllImages[] = $file;
    }
   closedir($handle);
   
   $sel_files = array_rand($arrAllImages, 3);
   echo "$arrAllImages[0].\n.$arrAllImages[1].\n.$arrAllImages[2]";  
   
}

using shuffle

<?php
  $imageDir = 'FuncIcon';
  $arrAllImages = array();
  if ($handle = opendir($imageDir)) {    
    while (false !== ($file = readdir($handle))) {
        if(($file == '.') || ($file == '..'))
          {
             continue;
             }
        $arrAllImages[] = $file;
    }
   closedir($handle);
   
   shuffle($arrAllImages);
   
   $i = 0;
   
   echo $arrAllImages[0].' '.$arrAllImages[1].' '.$arrAllImages[2];  
   
}
 
?>

These codes not very elegant but work in both the cases.
Maybe you have forgotten to take care of the . and ..
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question