PDA

View Full Version : image rotator php (array)


m1a2x3x7
07-12-2007, 01:49 PM
I needed a script for an image rotator for a site I'm working on and found this code.

<?php
function randomImage ( $array ) {
$total = count($array);
$call = rand(0,$total-1);
return $array[$call];
}

$my_images = array (
"red.gif",
"green.gif",
"blue.gif",
);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<?php
echo '<img
src="images/'.randomImage($my_images).'"
alt="Random Image" />';
?>
</body>
</html>

I've gotten everything thing to work just fine. But I haven't spent much time working with arrays and I don't really like using someone else's script without knowing exactly how it works.

I don't exactly understand how this part works.

function randomImage ( $array ) {
$total = count($array);
$call = rand(0,$total-1);
return $array[$call];
}

could someone explain it for me. Also are count and rand built in functions?

Thanks

davidj
07-12-2007, 02:10 PM
do you know much PHP?

m1a2x3x7
07-12-2007, 02:38 PM
sure do, I mainly work on storing and retrieving data, and creating forms but haven't done much with arrays.

davidj
07-12-2007, 03:38 PM
ok


function randomImage ( $array ) { //<< set function and argument

$total = count($array); //<< argument is an array so count keys and assign to $total var.

$call = rand(0,$total-1); //<< assign a random number to $call between 0 and $total.

return $array[$call]; //<< return array value by specifying key.

}


this is the array here...

$my_images = array (
"red.gif",
"green.gif",
"blue.gif",
);

and this is how the function is called...


randomImage($my_images).