Mohamed Hassan
Mohamed Hassan

Reputation: 1619

how to get a random element in an array and how to get a random row from mysql?

I have been asked to get related stuff to what the user has in his items

so as far as the database was created this items table stores the category name so, i thought to get the category name and save it into an array

and then do a for loop and get one random value from it

and after that get a random row from mysql database so anyone has an idea how to do this

in other words i want to know how to get a random value from an array and a random row from mysql

Thanks in advance.

Upvotes: 3

Views: 2331

Answers (3)

user783388
user783388

Reputation:

quote from http://php.net/manual/de/function.rand.php:

ilya dot iz at i dot ua 27-Jul-2011 08:09 I had to come up with a quick way to get a random row from a table, and came up with the following: ...

Should be easy to get a random value from an array with something like rand(0,count(arrayvar))

Upvotes: 0

liquorvicar
liquorvicar

Reputation: 6106

To get a random element from an array in PHP you can use array_rand.

To get a random row from a MySQL query you can use RAND() so something like

ORDER BY RAND() LIMIT 1

But note that this method in MySQL can have performance implications.

Upvotes: 2

sujal
sujal

Reputation: 1050

use

 $rand_keys = array_rand($input, 1);

see example http://php.net/manual/en/function.array-rand.php for php and for mysql

 SELECT * FROM tbl_name ORDER BY RAND() LIMIT 1

use this

Upvotes: 3

Related Questions