Jump to content

random pick do while


paulonline2501

Recommended Posts

hi, im trying to show three random pics from a folder and make sure the same pic dosnt get shown more than once. ive got it picking a random pic, but for some reason pics that i add to my $alreadyUsedImages variable are being displayed. the strpos seems to working as i tested by putting echos for true or false in there [not in code shown], i think its something to do with the strpos not working correctly!!sometimes images show up even when they've been displayed. it doesnt seem the strpos is getting consistent matches.this may have something to do with the $randomImage including the path with forward slashes.

<table class="gallery"><?php$alreadyUsedImages = "";$imagesDir = '../_images/gallery/';$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); $c=1;do{  $randomImage = $images[array_rand($images)];  if(strpos($alreadyUsedImages, $randomImage)==false)  {   $c++;   echo "<tr><td><img src=\"$randomImage\" alt\"\" /></td></tr>";   $alreadyUsedImages .= $randomImage;  }else}while ($c<=3);?></table>

Edited by as_bold_as_love
Link to comment
Share on other sites

One issue is that you're using loose comparison instead of strict comparison. strpos could return 0 meaning that the string starts with the substring, and since you're loosely comparing it with false, 0 loosely equals false so that if statement will be true. The manual for strpos indicates that you should use strict comparison, so that it compares the type in addition to the value. Another issue is that you're lumping all of the filenames together without a delimiter or anything. If you already have "11image.jpg" or something, and you're searching for "1image.jpg", it's going to find the substring. It would be better if you put those filenames in an array instead of a string, and use in_array to figure out if it's already there.

  • Like 1
Link to comment
Share on other sites

Great! thanks justsomeguy. both your suggestions worked, but ive gone with the array answer as it seems seems like the most sophisticated.

<?php$alreadyUsedImages = array();$imagesDir = '../_images/gallery/';$images = glob('../_images/gallery/*.{jpg,jpeg,png,gif}', GLOB_BRACE);$count=0;do{  $randomImage = $images[array_rand($images)];  if(!in_array($randomImage, $alreadyUsedImages))  {   $count++;   echo "<img src=\"$randomImage\" alt\"\" />";   $alreadyUsedImages[$count] = $randomImage;   //echo("false");  }  else{   //echo("true");  }}while ($count<=3);?>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...