Reputation: 28188
I'm trying to output a random selection of items stored in an array. There are three different arrays, and I want to output four items from each one. So 12 words to appear on the page.
Here is an example of the live site. Where you see the white squares, they're supposed to be words but I can't get it working: http://francesca-designed.me/create-a-status/
I have three arrays with 20 words each:
<?php
$poolOne=array("sparkly","sporty","happy","confident","awesome","funny","awkward","mad","silly","dynamic",
"handsome","merry","horrid","funky","loud","chirpy","posh","clever","pretty","athletic");
shuffle($poolOne);
$poolTwo=array("pink","purple","melon","lemon","lime","red","blue","peach","rouge","green",
"ginger","blonde","brown","yellow","gold","violet","rainbow","maroon","indigo","silver");
shuffle($poolTwo);
$poolThree=array("zebra","lion","tiger","fish","ktten","butterfly","octopus","squid","puppy","bug",
"spider","cat","hamster","newt","frog","monkey","dog","rabbit","pig","sheep");
shuffle($poolThree);
?>
I've attempted to use shuffle()
to shuffle up the numbers, and then call them out into my span
randomly:
<div class="words one">
<span><?php for($i=0;$i<4;$i++) {echo $poolOne[$i];} ?></span>
<span><?php for($i=0;$i<4;$i++) {echo $poolOne[$i];} ?></span>
<span><?php for($i=0;$i<4;$i++) {echo $poolOne[$i];} ?></span>
<span><?php for($i=0;$i<4;$i++) {echo $poolOne[$i];} ?></span>
</div>
I'm guessing this is not correct, or that I've done something wrong.
Ultimately I need to iterate through each array and output a random 4 into the spans.
Upvotes: 1
Views: 75
Reputation: 173662
Instead of shuffle()
you can use array_rand()
:
foreach (array_rand($poolOne, 4) as $key) {
echo $poolOne[$key];
}
foreach (array_rand($poolTwo, 4) as $key) {
echo $poolTwo[$key];
}
foreach (array_rand($poolThree, 4) as $key) {
echo $poolThree[$key];
}
The function returns an array of random (unique) keys of the array that you pass. If you only need four random elements of the array, this would be preferred over shuffle()
which modifies the whole array.
Does it matter that my arrays are below this in the code?
Yes, it does. The arrays MUST be declared above this code, otherwise they're undefined by the time your code runs.
Upvotes: 2
Reputation: 3355
Francesca - I am using Jack's suggestion to use array_rand
.
Please remove your shuffle
calls, and instead of that use this:
<div class="words one">
<span><?php foreach( array_rand( $poolOne, 4 ) as $key ) { echo $poolOne[ $key ] ; } ?></span>
<span><?php foreach( array_rand( $poolTwo, 4 ) as $key ) { echo $poolTwo[ $key ] ; } ?></span>
<span><?php foreach( array_rand( $poolThree, 4 ) as $key ) { echo $poolThree[ $key ] ; } ?></span>
</div>
I am perfectly okay if you mark Jack's answer. I am upping his as he pointed out to use array_rand().
Upvotes: 0