Solved

php - display images

Posted on 2012-04-09
12
200 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
 
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 108

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

863 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now