Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

php - display images

Posted on 2012-04-09
12
Medium Priority
?
212 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 30

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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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 30

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 111

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 2000 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
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…

688 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