-1

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));
5
  • use shuffle to randomize, and loop from 0 to 5. Simple google would have solved that one for you. Commented Dec 9, 2013 at 13:54
  • 1
    post your whole code, since you're pulling from a mysql source randomise the result set in query ORDER BY field` RAND` type thing you can also use LIMIT to limit the amount of results returned ie: LIMIT 0,5 will pull out only 5 results Commented Dec 9, 2013 at 13:54
  • In what way does this differ from your previous question? Displaying and Randomising php Arrays Commented Dec 9, 2013 at 13:54
  • php.net/manual/de/function.array-slice.php Commented Dec 9, 2013 at 14:03
  • um. array_rand($new_array, 5); Commented Dec 9, 2013 at 14:04

2 Answers 2

1

Easiest solution...

array_rand($array, 5);

PHP array_rand()

Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.