Reputation: 37
Is there any way in PHP to pick a random array from a list of arrays? This is my code:
$array1 = "FFFFFF 000000 111111 222222 333333 444444";
$array2 = "1111 2222 3333 4444 5555 6666";
$array3 = "111 222 333 444 555 666";
$array4 = "11 22 33 44 55 66";
$array5 = "a b c d e f";
$array6 = "1 2 3 4 5 6";
I want to make it so it picks a random array from that list of arrays, but I just cannot figure out how. I tried
$array . rand(1,9)
but unfortunately, PHP won't compile that like I want it to..
Upvotes: 0
Views: 92
Reputation: 13693
You can do it like this:
$array1 = "FFFFFF 000000 111111 222222 333333 444444";
$array2 = "1111 2222 3333 4444 5555 6666";
$array3 = "111 222 333 444 555 666";
$array4 = "11 22 33 44 55 66";
$array5 = "a b c d e f";
$array6 = "1 2 3 4 5 6";
$a = rand(1,6);
$str = 'array'.$a;
$arr = ${$str};
var_dump($arr);
/*
This would give you random array variables like this:
- $array2
- $array5
- $array1
- $array3
- ...
*/
Hope this helps!
Upvotes: 0
Reputation: 1476
If you were to place all of those arrays in another, you could use array_rand
to select a random one.
http://php.net/manual/en/function.array-rand.php
This may not work for you depending on where you're getting your input from, but I would prefer this solution to generating a random number between two hard limits, as the former is dynamic (it doesn't matter how many entries are in the array of arrays), while the latter is not (though it could be made to be).
As GordonM pointed out, array_rand
uses the libc random number generator, which is known to be slower than some alternatives. A dynamic alternative using a better random number generator would be to use mt_rand
, using the length of the array as a maximum:
$array = array(
// all your other arrays here
);
$selected = $array[mt_rand(0, count($array) - 1)];
EDIT: As pointed out Jacopo in the comments, it's also worth noting that your arrays are currently strings.
$array1 = "FFFFFF 000000 111111 222222 333333 444444";
Should be (I assume):
$array1 = array('FFFFFF', '000000', '111111', '222222', '333333', '444444');
Upvotes: 1
Reputation: 316
You have a simple variable, not an array. Try this:
$array1 = "FFFFFF 000000 111111 222222 333333 444444";
$array2 = "1111 2222 3333 4444 5555 6666";
Then convert to array:
$a = explode(" ", $array1);
$b = explode(" ", $array2);
And finally, print:
echo array_rand($a,3);
echo array_rand($b,3);
Regards
Upvotes: 0