I have 60 images but I want to randomly show 20 from 1 to 60.
My code is something like this, it shows 60
<?php
for( $i = 1; $i < 61; $i++ )
{
print '<a href="javascript:;"><img src="images/items/' . $i . '.png" class="allitems item' . $i . '" /></a>';
}
?>
I found PHP function RAND(), but unable to implement, any help would be appreciated.
Try functions
range()
andarray_rand()
:UPDv1: With
for
-loop:UPDv2:
I've misread
array_rand()
s manual. It returns array keys instead of elements. Here is multipurpose version (fix witharray_flip()
):And a shortcut function (negatives safe, and overall count safe):
There is another way for those, who needs non-growing random sequence. Use this:
UPDv3:
Another way, used
range()
+shuffle()
+array_slice()
: