0

Possible Duplicate:
Get random item from array

I need a code to set a random string for a variable. of course I have the string and they are not generated. I can put the strings in the array

$strings= array('one', 'two', 'yes', 'no', 'yeaa');
$random_str = ????

I need $random_str to be one or no or maybe two. Totally randomly from $strings.

rand and shuffle function didn't do that for me simply, and I'm beginner in php, so I need your help. so thank you guys for helping me

Community
  • 1
  • 1

3 Answers3

5

You can use array_rand to get a random element from an array:

$strings= array('one', 'two', 'yes', 'no', 'yeaa');
$random_str = $strings[array_rand($strings)];
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
0

Or you can just use the rand() function.

$strings= array('one', 'two', 'yes', 'no', 'yeaa');
$random_str = $strings[rand(0,4)];
Ed Manet
  • 3,118
  • 3
  • 20
  • 23
0

You can use:

<?php

mt_srand(time() * 1000);

$strings= array('one', 'two', 'yes', 'no', 'yeaa');
$ramdom_str = $strings[mt_rand(0, sizeof($strings)-1)];

?>

mt_srand and mt_rand are better implementations of rand and srand

Yago Riveiro
  • 727
  • 13
  • 28