random input

6 posts by 2 authors in: Forums > CMS Builder
Last Post: November 4, 2011   (RSS)

By Toledoh - November 2, 2011

Hi all...

I have a loop that goes

<?php foreach ($productsRecords as $record): ?>
<a href="#" class="random">Link here</a>
<?php endforeach ?>


with the class="random", I want a random item to appear from a list of items "red,blue,green" etc

I can hard code the list, or create the list in cmsb...
Cheers,

Tim (toledoh.com.au)

Re: [Toledoh] random input

By Toledoh - November 3, 2011

Got it!

<?php $input = array("blue", "green", "red", "yellow"); $rand_keys = array_rand($input, 2); echo $input[$rand_keys[0]] . "\n"; ?>
Cheers,

Tim (toledoh.com.au)

Re: [Toledoh] random input

By Toledoh - November 3, 2011

Hi guys,

This code doesn't seem to be working as well as I thought.

<?php $input = array("blue", "green", "red", "yellow"); $rand_keys = array_rand($input, 2); echo $input[$rand_keys[0]] . "\n"; ?>">

It seems that I'm not returning any "yellows" and some "red"... any thoughts on why?
Cheers,

Tim (toledoh.com.au)

Re: [Toledoh] random input

By Dave - November 4, 2011

Hi Tim,

Try this example:
foreach (range(1,100) as $count) {
$allValues = array("blue", "green", "red", "yellow");
$randomValue = $allValues[ array_rand($allValues,1) ];
echo "$randomValue<br/>\n";
}


Let me know if that works better for you.
Dave Edis - Senior Developer
interactivetools.com

Re: [Toledoh] random input

By Dave - November 4, 2011

Hi Tim,

Glad it's working! You can actually trim the code down a bit more, I just had the foreach loop in there to show multiple values. Here's an even shorter version:

<?php
$allValues = array("blue", "green", "orange", "yellow");
$randomValue = $allValues[ array_rand($allValues,1) ];
echo "$randomValue\n";
?>


Cheers!
Dave Edis - Senior Developer
interactivetools.com