How do i randomize my array elements and limit number of items to be displayed to 5
My code is:
while($row = mysql_fetch_assoc($result))
{
$new_array[] = $row;
}
echo '<pre>'; print_r(($new_array));
shuffle($array);
$pointer = 0;
foreach($array as $value) {
if($pointer > 4) break;
echo $value;
$pointer++
}
shuffle will randomize your array, then you start a pointer at 0 and increment it in your foreach loop, if you the pointer is more than 4 you break the foreach loop
as another solution, you could use a for loop
shuffle($array);
for($i = 0; $i < 5; $i++) {
echo $array[$i];
}
and one more solution for limiting, since you're pulling the array for your database by a query, you can limit the number of rows returned by a number you choose by adding LIMIT 5 at the end of your query.
shuffleto randomize, and loop from0to5. Simple google would have solved that one for you.ORDER BYfield` RAND` type thing you can also useLIMITto limit the amount of results returned ie:LIMIT 0,5will pull out only 5 results