Solved

php - display images

Posted on 2012-04-09
12
199 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
Comment Utility
can u post your code?
0
 
LVL 1

Author Comment

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

Expert Comment

by:Olaf Doschke
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 9

Expert Comment

by:rinfo
Comment Utility
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
Comment Utility
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
Comment Utility
im testing the provide code but its not working and i dont see any errors..
0
 
LVL 9

Expert Comment

by:rinfo
Comment Utility
can you post the codes you are using
0
 
LVL 9

Expert Comment

by:rinfo
Comment Utility
can you post the codes you are using
0
 
LVL 9

Accepted Solution

by:
rinfo earned 500 total points
Comment Utility
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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…

772 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

13 Experts available now in Live!

Get 1:1 Help Now