array random and print help.

Hey guys. im such a noob i really dont know how to do this… ive tried few things but never succeeded .

im trying to make an array of php files… then random them… and then print one of them (and by print i dont mean print the file name… i need to print the content of it as a php file hope you understand)

thanks in advance.

Hi there,

You did not specify how the array of files is being populated. I don’t know if you’ve already got that sorted, but if not please check out the examples below. (I assume throughout these examples that the files are in a sub-folder called “includes”, change the folder name to suite your needs or if they are in the same directory as the file being called, just remove “includes/” wherever it is used).

Array Creation #1 (manual input):
[php]$myfiles = array(“includes/file2.php”,“includes/file3.php”,“includes/file9.php”);[/php]

Array Creation #2 (get files from a directory):
[php]$directory = scandir("./includes/");
$myfiles = array();
foreach($directory as $file)
if($file != “.” && $file != “…”)
$myfiles[] = $file;

Either method leaves us with an array called $myfiles, filled the the files that you want choose a random file from. For which you can just use:
[php]include ‘./includes/’.$myfiles[array_rand($myfiles)];[/php]

Broken down version:
[php]$filepath = “./includes/”;
$randomkey = array_rand($myfiles); //Will return a random key from the array
$filepath .= trim($myfiles[$randomkey]); //Append the file path string with the file name
include $filepath;[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service