PHP How to get a random value from array

Go To StackoverFlow.com

0

i have this array

$row4 = mysql_fetch_array($sql_res);

can anyone help me how to get a random value of $row4['response']?

the $row4 does not have constant values...
but for now $row4 contains

Array ( [0] => 3 [id] => 3 [1] => where is dryad [react] => where is dryad [2] => Dryad is found in the farthest part of the Dark wilderness. [response] => Dryad is found in the farthest part of the Dark wilderness. [3] => [review] => ) 1
2012-04-04 00:57
by Julian Paolo Dayag
What does contain $row4['response'] - Salepate 2012-04-04 00:58
See http://php.net/array-ran - Pete 2012-04-04 00:58
Or do you want a random row? http://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sq - A B 2012-04-04 01:00
@Salepate Array ( [0] => 3 [id] => 3 [1] => where is dryad [react] => where is dryad [2] => Dryad is found in the farthest part of the Dark wilderness. [response] => Dryad is found in the farthest part of the Dark wilderness. [3] => [review] => ) - Julian Paolo Dayag 2012-04-04 01:02
@alberge no.... if i use ORDER by rand() my other strings will be affected.. - Julian Paolo Dayag 2012-04-04 01:03
@pete please show some example.. - Julian Paolo Dayag 2012-04-04 01:06


3

As your code is right now, you would only receive back one query row. This row would just contain your field values for that row. If you are indeed just trying to get a random field value from that single row, you would use:

$randomKey = array_rand($row4,1);

If you meant to ask for a random row from your query, you can do this one of two ways:

1) Use array_rand to grab a random row and place into $randomRow:

while($row = mysql_fetch_array($sql_res)) $rows[] = $row;
$randomRow = array_rand($rows);

2) In your query you can specify to only grab 1 random row rather than every result:

SELECT col1 FROM tbl ORDER BY RAND() LIMIT 1;

2012-04-04 01:07
by VictorKilo
sir can you tell me how.... to get the response value of the random row???? i only want the random respons - Julian Paolo Dayag 2012-04-04 01:13
i tried $randomKey['response'] but no result... - Julian Paolo Dayag 2012-04-04 01:13
If you are using the $randomKey method tat means that you are not receiving an array, only a single random value from your one row returned. If you want to reference a random row (which would be an array) use one of the other methods - VictorKilo 2012-04-04 03:28
@JulianPaoloDayag Did you get it working - VictorKilo 2012-04-04 16:14
Ads