Link to home
Start Free TrialLog in
Avatar of ct8270
ct8270

asked on

Randomly rotate 5 different PHP header files.

I need to rotate 5 different PHP header files that are include files for a header of a website.
Avatar of ldbkutty
ldbkutty
Flag of India image

you want to include any of the 5 header file randomly ?
<?
$folderPath = '/path/to/header_files';
if ($handle = opendir($folderPath)) {
   /* This is the correct way to loop over the directory. */
   while (false !== ($file = readdir($handle))) {
       $fileArray[] = $file;
   }
   closedir($handle);
}

shuffle($fileArray);

include "$fileArray[0]";

?>
ASKER CERTIFIED SOLUTION
Avatar of markdoc
markdoc

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
yes, thats more simple :) But there is shuffle() function that can be used rather than using count() and rand() functions.

<?php

$includespath = "the_includes_path/";
$arrHeaders = array(
    "header1.inc",
    "header2.inc",
    "header3.inc",
    "header4.inc",
    "header5.inc");

shuffle($arrHeaders);
include($includespath . $arrHeaders[0]);

?>
Avatar of markdoc
markdoc

Idbkutty, I used the rand() function because shuffle(), as its name suggests, should use *more* processing time than rand(), because rand() only gives you a random integer and not mess around with an array's elements. Although good for a small number of elements like 5, shuffle() would be much, much slower when dealing with larger arrays in general. ;)

Anyway, a *dangerous* optimization to my former post would be:

<?php

$includespath = "the_includes_path/";
$arrHeaders = array(
    "header1.inc",
    "header2.inc",
    "header3.inc",
    "header4.inc",
    "header5.inc");

$elements = 5;   // Since you've already hard-coded the filenames why not hardcode this too?
include($includespath.$arrHeaders[rand(0, $elements - 1)]);

?>
yes, you are a keen programmer :)
Thanx Idbkutty, but your 54 K+ points makes you the more prolific one. ;)
Avatar of ct8270

ASKER

Worked perfectly! Thanks for all your help.