spinPHP

Random Sections

"); insertRandomIncludeFile("include1.php", "include4.php", "include3.php"); ?>

This PHP function displays random contents in a Web page. Click the refresh button in your browser to view how the contents in the the leftmost column of this page is randomly changed when the page is loaded by the browser.

This action is performed by a PHP function which we have named insertRandomIncludeFile, and it is called with a list of file names:

insertRandomIncludeFile("include1.php", "include2.php");

include1.php and include2.php are two existing files with HTML or PHP contents. One of the files is randomly selected by the function, and the contents in this file is inserted into the HTML page where the insertRandomIncludeFile("include1.php", "include2.php") funcion call is placed.

In this example the function is called from two places in the source for the leftmost column in this page, like this:

<? 
insertRandomIncludeFile("include1.php", "include2.php");
echo("<BR>");
insertRandomIncludeFile("include1.php", "include4.php", "include3.php");
?>

As you can see in the last call to insertRandomIncludeFile() you are able to specify several files to be randomly selected by the function.

Below is the source and some coding comments for the PHP function insertRandomIncludeFile()

<?
function insertRandomIncludeFile () 
{
	$numArgs = func_num_args();	
	$index = rand(0, $numArgs-1);
	include func_get_arg($index);
}
?>

The func_num_args counts how many strings that are sent to the function.

The line $index = rand(0, $numArgs-1) sets the variable $index to a random number between 0 and the number of strings sent to the function.

func_get_arg($index) returns string number $index from the strings sent to the function, and this file is included in the HTML page via PHP's include command.

This PHP code example is copyright © 2002-2003 Optima System. All rights reserved worldwide. Unauthorized distribution prohibited. SpinPHP™ User License.