2 Replies - 461 Views - Last Post: 08 December 2010 - 11:54 AM Rate Topic: -----

#1 Galaxy_Stranger  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 100
  • Joined: 07-February 06

PHP Array Problem - I think

Posted 07 December 2010 - 10:13 PM

In the past, I've used a hard-coded javascript function to grab a random number to choose an index from an array - which contains a string to an image file name, which is then displayed on the web page, thus randomizing the image whenever the page is refreshed.

I've decided to move the logic to PHP. So, I open the directory and stick all the file names in an array, randomize a number from zero to the total count of array indices and use that to display the image.

At first, this worked great - but I started noticing that images would randomly not be displayed. So I started keeping track of the index used - and it was consistently several of the indices - 3, 11, etc. Of course, I checked the files and none of them are corrupt.

This is a very weird problem. Anyone have any ideas?

<?php
    //	look at the directory - count the number of images and stick them into an array:
    $myDirectory = opendir("./images") ;

    //	Get each file:
    while($file = readdir($myDirectory))
    {
      $dirArray1[] = $file ;
    }
    closedir($myDirectory) ;

    //	Generate a random number:
    $fileIndex1 = rand(0,(count($dirArray1))) ;

    echo "
        <div><img src=\"./images/$dirArray1[$fileIndex1]\" alt=\"\" /></div>
    " ;
?>

This post has been edited by Galaxy_Stranger: 07 December 2010 - 10:17 PM


Is This A Good Question/Topic? 0
  • +

Replies To: PHP Array Problem - I think

#2 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3075
  • Posts: 10,783
  • Joined: 08-August 08

Re: PHP Array Problem - I think

Posted 08 December 2010 - 08:56 AM

readdir() doesn't just read file names. It reads directory names too, such as "." and ".." as well as any subdirectories. Those will not show up as images.
Was This Post Helpful? 1
  • +
  • -

#3 Galaxy_Stranger  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 100
  • Joined: 07-February 06

Re: PHP Array Problem - I think

Posted 08 December 2010 - 11:54 AM

Ah - thanks.

This method also seems to be more taxing on the web server, what with the file system interaction every time. Much of the time some of the content isn't even displayed.

I think I'll stick with the javascript version - or make a database entry for each image to be written to html.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1