My name is Shruti.I'm new to php. I have a program which displays images randomly, there are about 200 images in my program.I want to display the random images with out repetition, can any one please help with this. here is my code.
Appreciate your help
Thank you.
I don't know whats about the $img_id but you could consider to use shuffle().
shuffle($file_array);
But then you loose the connection to $img_id. You could (I am not sure if this is the best solution), build your array this way:
$file_array = array(
array("images/bag200.bmp", 1),
array("images/bag178.bmp", 1),
array("images/bag004.bmp", 0,
...
);
In the long run, it is probably better to store all the image paths in a CSV file or even a database. Believe me, you don't want to maintain an array with > 200 entries manually ;)
You can loop over images this way (they are in random order now):
<?php foreach($file_array as $image): ?>
<img src="<?php echo $image ?>" />
<?php endforeach; ?>
If you only want to display a subset of the images, randomly chosen, you can do this:
$n = 20; // want to display 20 images
$rand = array_rand(range(0,200), $n); // draw keys randomly
shuffle($rand); //shuffle keys
foreach($rand as $r) {
echo '<img src="' . $file_array[$r] . '" />';
}
Some comments on your code:
$ran = array_rand($file_array);
$ran contains a key randomly chosen from the images.
for ($i=0;$i<200;$i++) {
//while (in_array($tst,$rand_array)){
$tst = $file_array[$ran];
$id = $img_id[$ran];//}
$rand_array[] = $tst;
$rand_id[] = $id;
}
You always pick the same entry from $file_array and $image_id because you never change $ran. That is way you get the same image 200 times.
If you want randomness but require uniqueness, you are looking for a quasi-random number generator. There are many different types with different properties. Look here for information on creating an algorithm: http://www.mathworks.nl/access/helpdesk/help/toolbox/stats/br5k9hi-8.html
Related
I am trying to display a certain amount of random images from one directory on my website without displaying duplicates.
I found this question: Display 2 random pictures PHP with no duplicates which partially answers my problem:
<?php
$pics = array('image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg');
$images = array_rand($pics, 2);
?>
<img src="images/<?php echo $pics[$images[0]]; ?>" />
<img src="images/<?php echo $pics[$images[1]]; ?>" />
The problem I have is that the images are uploaded to the folder with completely different/random names such as 1a2265fg65444.jpg 55v4423097ww6.jpg etc, so I can't manually add them to the $pics array. I need to somehow scrape the directory for *.jpg and have the array generated automatically
I did try Michal Robinsons answer on Show Random images from a folder without repeating using JS or PHP but couldn't get it to print anything for some reason:
$all_images = glob("/images/photos/{*.jpg}", GLOB_BRACE);
shuffle($all_images);
$images = array();
foreach ($all_images as $index => $image) {
if ($index == 15) break; // Only print 15 images
$image_name = basename($image);
echo "<img src='/images/photos/{$image_name}' />";
}
Perhaps I'm missing something?
Any pointers would be simply awesome.
Many thanks
try this
$scan = scandir("/images/photos/");
shuffle($scan);
$r = rand(2, count($scan)); // maybe (count($scan) - 1)
printf("<img src='/images/photos/%s' />", basename($scan[$r]));
Thanks Aron, but I managed to fix it by changing:
glob("/images/photos/ to
glob("images/photos/
To complicate things further though, I just realized I need to show 1 image from a 1st folder followed by another image from a 2nd folder, and repeat this about 5 times, still without showing any duplicate :/ This is as far as I have got, but seem to be digging a bigger hole that doesn't work, as I'm stuck at the foreach...:
$all_images1 = glob("images/photos/{*.jpg}", GLOB_BRACE);
$all_images2 = glob("images/photos1/{*.jpg}", GLOB_BRACE);
shuffle($all_images1);
shuffle($all_images2);
$images1 = array();
$images2 = array();
$class = 1;
foreach ($all_images1 as $index1 => $image1) {
if ($index1 == 10) break; // Only print 15 images
$image_name1 = basename($image1);
echo "<img src='/images/photos/{$image_name1}' class='image".$class++."' /> <img src='/images/photos1/{$image_name2}' class='image".$class++."' />";
}
Am I going in the wrong direction to do this?
Thanks Ted
I am successfully able to get random images from my 'uploads' directory with my code but the issue is that it has multiple images repeat. I will reload the page and the same image will show 2 - 15 times without changing. I thought about setting a cookie for the previous image but the execution of how to do this is frying my brain. I'll post what I have here, any help would be great.
$files = glob($dir . '/*.*');
$file = array_rand($files);
$filename = $files[$file];
$search = array_search($_COOKIE['prev'], $files);
if ($_COOKIE['prev'] == $filename) {
unset($files[$search]);
$filename = $files[$file];
setcookie('prev', $filename);
}
Similar to slicks answer, but a little more simple on the session front:
Instead of using array_rand to randomise the array, you can use a custom process that reorders based on just a rand:
$files = array_values(glob($dir . '/*.*'));
$randomFiles = array();
while(count($files) > 0) {
$randomIndex = rand(0, count($files) - 1);
$randomFiles[] = $files[$randomIndex];
unset($files[$randomIndex]);
$files = array_values($files);
}
This is useful because you can seed the rand function, meaning it will always generate the same random numbers. Just add (before you randomise the array):
if($_COOKIE['key']) {
$microtime = $_COOKIE['key'];
else {
$microtime = microtime();
setcookie('key', $microtime);
}
srand($microtime);
This does means that someone can manipulate the order of the images by manipulating the cookie, but if you're okay with that this this should work.
So you want to have no repeats per request? Use session. Best way to avoid repetitions is to have two arrays (buckets). First one will contains all available elements that your will pick from. The second array will be empty for now.
Then start picking items from first array and move them from 1st array to the second. (Remove and array_push to the second). Do this in a loop. On the next iteration first array won't have the element you picked already so you will avoid duplicates.
In general. Move items from a bucket to a bucket and you're done. Additionally you can store your results in session instead of cookies? Server side storage is better for that kind of things.
I have a folder unit_images that is full of images with random names except they have a prefix that corresponds to a PRIMARY KEY in a db table.
1_4534534fw4.jpg
2_43534tw4t45.png
You get my point. I am using YoxView to view images and am doing something like this:
<?php
$query = "SELECT id FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '<div class="yoxview">';
while ($row = mysqli_fetch_assoc($result))
{
echo '<img src="unit_images/01.jpg" alt="First" title="First image" />
<img src="unit_images/02.jpg" alt="Second" title="Second image" />'
}
echo '</div>';
?>
I want to list the images from my folder unit_images WHERE the unit is the one currently being shown.I just do not know how to tell PHP the filename. I want to do something similar to a 1_% in SQL. Does that make sense? Since I do not know what the rest of the filename looks like I just need to tell php it doesn't matter.
The closest equivalent to SQL's % wildcard that works for files is the shell's * wildcard, which is available in php through the glob() function. You can iterate through its results as follows:
foreach (glob("unit_images/1_*.jpg") as $filename) {
echo '<img src="unit_images/' . htmlspecialchars(basename($filename))
. '" />';
}
If I understand you correctly, you want to get a list of items in a directory with a certain prefix.
Step 1 (use sandir() to determine the items in the directory):
$files = scandir('unit_images');
Step 2 (eliminate the unwanted image names):
for ($i=0; $i<count($files); i++)
{
$file = $files[i];
$prefix = explode("_", $file)[0];
if ($prefix != $_GET['id'])
{
unset($files[i]);
}
}
$files is now an array of only the file names prefixed with $_GET['id]
My advice would be to store the whole name of the file in a column so that you can reference it directly instead of having to search in the file system for a matching name.
Having said that, you can search for a file using the glob PHP function.
Maybe you can do something like this:
glob("unit_images/<YOUR_PRIMARY_KEY>_*.{png,jpg}", GLOB_BRACE);
my current script is this:
$attach[] = array('pics/pic1.jpg', 'image/jpeg');
how can i change it, so it pics a random picture in the pics/ folder instead of a specified?
Theres like 20 pics in pics/
I want the script uses a random.
You can use array_rand() for this. If you don't already have all files in an array, you can easily do it with glob()
$all_pics = array();
foreach (glob("./pics/*") as $filename)
$all_pics[] = array($filename, filetype($filename));
$random_pic = array_rand($all_pics);
This is universal, if you are sure your pictures are all named pic1, pic2, etc., it is probably better to just generate a random number and use it as in sal00ms answer.
You can try something like this:
$attach[] = array('pics/pic'.rand(1,20).'.jpg', 'image/jpeg');
And rename your files pic1,pic2...,pic20
You may also try something like this
function getRandomImage()
{
// add more images in the array
$pics = array('pics/pic1.jpg', 'image/pic.jpeg', 'photo/pic.png');
$i = rand(0, count($pics)-1);
return $pics[$i];
}
$image = getRandomImage();
First generate a random number!
$random_number = rand(0, 19);
Then, get all the pics of the folder in an array.
$pics = glob("pics/*");
Then, get the random pic from the array using random number
$random_pic = $pics[$random_number];
You can simplify it in one step as
$random_pic = glob("pics/*")[rand(0, 19)];
My website has an image in a certain place and when a user reloads the page he should see a different image on the same place. I have 30 images and I want to change them randomly on every reload. How do I do that?
Make an array with the "picture information" (filename or path) you have, like
$pictures = array("pony.jpg", "cat.png", "dog.gif");
and randomly call an element of that array via
echo '<img src="'.$pictures[array_rand($pictures)].'" />';
Looks weird, but works.
The actual act of selecting a random image is going to require a random number. There are a couple of methods that can help with this:
rand() is used to generate a random number.
array_rand() is used to select a random element's index from an array.
You can think of the second function as a shortcut for using the first if you're specifically dealing with an array. So, for example, if you have an array of image paths from which to select the one you want to display, you can select a random one like this:
$randomImagePath = $imagePaths[array_rand($imagePaths)];
If you're storing/retrieving the images in some other way, which you didn't specify, then you may not be able to use array_rand() as easily. But, ultimately, you need to generate a random number. So some use of rand() would work for this.
If you store the information in your database, you can also SELECT a random image:
MySQL:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
PgSQL:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
Best,
Philipp
An easy way to create random images on popup is this method below.
(Note: You have to rename the images to "1.png", "2.png", etc.)
<?php
//This generates a random number between 1 & 30 (30 is the
//amount of images you have)
$random = rand(1,30);
//Generate image tag (feel free to change src path)
$image = <<<HERE
<img src="{$random}.png" alt="{$random}" />
HERE;
?>
* Content Here *
<!-- Print image tag -->
<?php print $image; ?>
This method is simple and I use this every time when I need a random image.
Hope this helps! ;)
I've recently written this which loads a different background on every pageload. Just replace the constant with the path to your images.
What it does is loop through your imagedirectory and randomly picks a file from it. This way you don't need to keep track of your images in an array or db or whatever. Just upload images to your imagedirectory and they will get picked (randomly).
Call like:
$oImg = new Backgrounds ;
echo $oImg -> successBg() ;
<?php
class Backgrounds
{
public function __construct()
{
}
public function succesBg()
{
$aImages = $this->_imageArrays( \constants\IMAGESTRUE, "images/true/") ;
if(count($aImages)>1)
{
$iImage = (int) array_rand( $aImages, 1 ) ;
return $aImages[$iImage] ;
}
else
{
throw new Exception("Image array " . $aImages . " is empty");
}
}
private function _imageArrays( $sDir='', $sImgpath='' )
{
if ($handle = #opendir($sDir))
{
$aReturn = (array) array() ;
while (false !== ($entry = readdir($handle)))
{
if(file_exists($sDir . $entry) && $entry!="." && $entry !="..")
{
$aReturn[] = $sImgpath . $entry ;
}
}
return $aReturn ;
}
else
{
throw new Exception("Could not open directory" . $sDir . "'" );
}
}
}
?>