Hi
I want to add a random element to my site.
On the right hand side there are a series of boxes with various features in them.
These are included in the main page.
The filenames of these sidebar boxes are sidebar01.php... sidebar10.php
I don't want to display all of these sidebar boxes at the same time.
To see what I mean about sidebar boxes take a look at http://www.dealer-world.it and look at the boxes on the right hand side.
What I want to do is take 3 at random from the selection of files.
I can generate a random number, but the bit I'm having trouble with is once that sidebar box is included making sure it can't be included again.
Also the number of sidebar boxes available to choose from varies...
I've set up a folder in my webspace called 'sidebar' and all the sidebar files sit in there.
Today there might only be three sidebar files, sidebar04.php, sidebar08.php and sidebar23.php
But tomorrow there might be a different selection of files...
sidebar01.php, sidebar05.php, sidebar45.php, sidebar21.php...
So what I need to do is this...
- Set up an array containing the sidebar file names which exist in the /sidebar folder
- Loop three times
- Each iteration generate a random number between 0 and the total number of entries in the array
- Include whatever filename that is
- Remove that item from the array
- Loop again until 3 have been done
I'm not sure how to read the contents of the /sidebar folder into an array. The problem is I want it to parse only files with .php extension into the array.
Also, once it's been included on the page, how do I then remove that index from the array?
Any ideas guys?
Thanks in advance
Ben
[SOLVED] read directory contents into an array
Moderator: General Moderators
[SOLVED] read directory contents into an array
Last edited by batfastad on Tue Jan 11, 2005 7:39 am, edited 1 time in total.
[SOLVED] read dir contents into array - random include
Hi
Just to let everyone know I've solved my problem by finding a couple of functions that do the trick for me.
array_rand()
Also managed to take into account that the array would contain 2 items of . and .. so have made sure they're excluded from my resulting $sidebarfiles array.
Hope this helps someone.
Thanks
Ben
Just to let everyone know I've solved my problem by finding a couple of functions that do the trick for me.
array_rand()
Code: Select all
// PARSE THE FILES IN THE $sidebar FOLDER INTO AN ARRAY
$sidebardir = "dwc-content/";
$sidebarfiles = array();
$open = opendir($sidebardir);
while ($currentfile = readdir($open)) {
if ($currentfile != "." && $currentfile != "..") {
$sidebarfilesї] = $currentfile;
};
};
closedir($open);
sort($sidebarfiles);
reset($sidebarfiles);
// CHOOSE 3 OF THEM AT RANDOM
$sidebardisplay = array_rand($sidebarfiles, 3);
echo $sidebarfilesї$sidebardisplayї0]] . "<br>\n";
echo $sidebarfilesї$sidebardisplayї1]] . "<br>\n";
echo $sidebarfilesї$sidebardisplayї2]] . "<br>\n";Hope this helps someone.
Thanks
Ben