Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

php - display images

Posted on 2012-04-09
12
Medium Priority
?
217 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 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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

This article discusses four methods for overlaying images in a container on a web page
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
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…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

885 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