Specifications

Reordering Arrays
For some applications, you might want to manipulate the order of the array in other ways. The
function shuffle() randomly reorders the elements of your array. The function
array_reverse() gives you a copy of your array with all the elements in reverse order.
Using shuffle()
Bob wants to feature a small number of his products on the front page of his site. He has a
large number of products, but would like three randomly selected items shown on the front
page. So that repeat visitors do not get bored, he would like the three chosen products to be
different for each visit. He can easily accomplish his goal if all his products are in an array.
Listing 3.1 displays three randomly chosen pictures by shuffling the array into a random order
and then displaying the first three.
L
ISTING 3.1 bobs_front_page.phpUsing PHP to Produce a Dynamic Front Page for
Bobs Auto Parts
<?
$pictures = array(“tire.jpg”, “oil.jpg”, “spark_plug.jpg”,
“door.jpg”, “steering_wheel.jpg”,
“thermostat.jpg”, “wiper_blade.jpg”,
“gasket.jpg”, “brake_pad.jpg”);
shuffle($pictures);
?>
<html>
<head>
<title>Bob’s Auto Parts</title>
</head>
<body>
<center>
<h1>Bob’s Auto Parts</H1>
<table width = 100%>
<tr>
<?
for ( $i = 0; $i < 3; $i++ )
{
echo “<td align = center><img src=\””;
echo $pictures[$i];
echo “\” width = 100 height = 100></td>”;
}
?>
</tr>
</table>
</center>
</body>
</html>
Using Arrays
C
HAPTER 3
3
USING ARRAYS
83
05 7842 CH03 3/6/01 3:42 PM Page 83