Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying and Randomising php Arrays

Tags:

arrays

php

mysql

I have an array displaying results as below:

Array
(
    [0] => 71
    [1] => 56
    [2] => 64
    [3] => 82
    [4] => 90
    [5] => 80
    [6] => 65
    [7] => 62
    [8] => 14
    [9] => 3
)

My code is:

while($row = mysql_fetch_assoc($result))
{   

  $show[] = $row['number'];

}
   echo '<pre>'; print_r($show);

How can I randomize the array contents and display them as 5 digits only e:g 71 64 14 80 82

like image 943
Des Avatar asked Nov 22 '25 11:11

Des


2 Answers

$rand5 = array_rand(array_flip($show), 5);
// we need array_flip because array_rand returns the keys

http://php.net/array_rand

http://php.net/array_flip

like image 162
Halcyon Avatar answered Nov 25 '25 03:11

Halcyon


I would go with shuffle to randomize the arrays, as per getting the 5 elements of teh array, it really depends on your need, what do you exactly want to accomplish, getting the first 5 elements, the last ones, or some other logic.

like image 24
Ma'moon Al-Akash Avatar answered Nov 25 '25 03:11

Ma'moon Al-Akash