Web design

Generating a Random Integer with PHP

This is a function I’ve found very useful in a number of Wordpress themes I’ve been developing, whereby I want to randomly select and display one of a set number of jpgs (called 1.jpg, 2.jpg, 3.jpg et cetera)

The magic function is rand() which returns a random integer. There are two uses

int rand  (void)
int rand (int $min , int $max)

If you don’t supply any variables, rand() returns a random integer between 0 and RAND_MAX. RAND_MAX is usually 32768 on Windows systems, if you need a higher value, then you need to specify a $min and $max variable to generate a larger range.

If you supply a range of integers to rand(), then the range of possible values between $min and $max inclusive.

Examples

<?php echo rand(); ?>

Could return integers such as 7734, 1981, 2, 0, 30929 etc.

<?php echo rand(1,5) ?>

Will return one of the following: 1,2,3,4,5.

<?php echo rand(15000,50000) ?>

Will return any integer between (and including) 15000 and 50000.

Post a Comment

I welcome your thoughts and comments. Please note that comments are moderated, therefore your comment will not appear immediately. Comments may be edited or deleted at my discretion. For more information please consult my comment policy.

Your email is never published nor shared. Required fields are marked *

*
*

Comment moderation is enabled. Your comment may take some time to appear.