Forum Moderators: coopster

Message Too Old, No Replies

limiting array results

         

Doood

5:35 pm on Mar 26, 2008 (gmt 0)

10+ Year Member



I've got a simple script that shuffles five url's and displays them randomly, but what if I only want to display three of the five instead of all of them?

I don't know how to randomly display only a portion of the links without all of them being shown.


<?php
$links = array(
"<a href=\"link1.php\">link1</a>",
"<a href=\"link2.php\">link2</a>",
"<a href=\"link3.php\">link3</a>",
"<a href=\"link4.php\">link4</a>",
"<a href=\"link5.php\">link5</a>",
);

shuffle($links);

foreach($links as $link) {
echo "<td>$link</td>";
}
?>

dreamcatcher

7:07 pm on Mar 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



// Restrict loop to 3 occurences using for loop..
for ($i=0; $i<3; $i++) {

// Get a random array slot..
$rand = rand(0,(count($links)-1));

// Echo link..
echo '<td>'.$links[$rand].'</td>';

}

dc

mooger35

7:32 pm on Mar 26, 2008 (gmt 0)

10+ Year Member



Rand won't guarantee unique results though.

$links = array(
"<a href=\"link1.php\">link1</a>",
"<a href=\"link2.php\">link2</a>",
"<a href=\"link3.php\">link3</a>",
"<a href=\"link4.php\">link4</a>",
"<a href=\"link5.php\">link5</a>",
);

shuffle($links);

for($i=0;$i<3;$i++){
echo $links[$i]."<br>\r\n";
}

Doood

7:32 pm on Mar 26, 2008 (gmt 0)

10+ Year Member



ha, that works perfect. Thanks a ton!

dreamcatcher

8:35 pm on Mar 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Rand won't guarantee unique results though.

Oops, indeed. Thanks mooger35.

dc