-1

I want to pick some value from array randomly, but I'm not sure about best way to do it(in terms of performance etc). I'm only a beginner, so I don't know many ways to random values and don't know how they affect performance and exact differences of them. For example: "mt_rand" is four times faster than "rand" function.

If I have this array of names:

$myarrayofnames = ["Marcelle","Caroll","Kristina","Tisha","Filomena","Vesta","Josphine"];

And I want to pick from them, what are my options?

winadalwin
  • 13
  • 1

1 Answers1

1

Note that mt_rand() and rand() just for generate random no.

From the Manual: mt_rand — Generate a better random value

From the Manual: rand — Generate a random integer

For your array you can use array_rand() for getting random value.

Example:

$myarrayofnames = ["Marcelle","Caroll","Kristina","Tisha","Filomena","Vesta","Josphine"];
$randomNo = array_rand($myarrayofnames,1);
echo $myarrayofnames[$randomNo]; // this will print the random value

If you just want only one single value from your array than you can just pass 1 in second param.

If you want more than one value from your array than you can pass no as per your array index count. In this case array_rand() will return an array.

If you want to learn about the Difference between mt_rand() and rand()

Community
  • 1
  • 1
devpro
  • 16,184
  • 3
  • 27
  • 38