chr
chr

Reputation: 1

About mt_rand of an array

I have a code which selects a random url from a folder like this:

<?php
  $urls = glob("videos/*.php");
  $random = mt_rand(0, count($urls) - 1);
  header ("location: ".$urls[$random]);
  exit;
?>

I had help with the $random function, but did not receive an explanation for it.

The code works perfectly. But I'm wondering why it looks like this:

mt_rand(0, count($urls) - 1);

Instead of this:

mt_rand(count($urls));

Upvotes: 0

Views: 1282

Answers (3)

trincot
trincot

Reputation: 350137

mt_rand can be called with either no arguments, or two, but not one.

If called with two arguments, it will generate an integer number between these two values, and these two bounding values themselves are potential candidates as well:

min
Optional lowest value to be returned
max
Optional highest value to be returned

Without arguments, the range is between 0 and some system dependent high natural number:

If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and mt_getrandmax().

This is different as in some other programming languages where without argument a fractional number is returned between 0 and (but not including 1).

Maybe you were thinking of java.util.Random.nextInt() which does accept one argument, and would work like you intended it, except that it is Java, and not PHP.

Upvotes: 0

adarshdec23
adarshdec23

Reputation: 231

No mt_rand(count($urls)); will not work. And mt_rand(0, count($urls)); will not always work as desired.

Explanation: count($any_array) will return lastIndex+1. For example

$a=array(10,20,30);
echo count($a); //3, but $a[3] is invalid

So you have the -1 bit. And mt_rand takes either 0 or 2 parameters.

Upvotes: 0

T.Z.
T.Z.

Reputation: 2162

Read the fine manual first, and then ask questions. :)

But as You already did I will try to explain.

mt_rand function gives You random number. When no arguments given, it wloud return random number from set [0,mt_getrandmax()]. You do not need this.

If You wloud execute it like this: mt_rand(count($urls)), You would receive error like this:

Warning: mt_rand() expects exactly 2 parameters, 1 given in

What You need is value from range [0,count($urls)-1], and this is what Your code does.

If You are wonderng about count($urls)-1 part, the count($ulrs) gives You the number of url, so if You have five of them, You will recive 5. But You need index of random url, and indexes in PHP begins at 0, so if You have five urls the last index of array will be 4.

Upvotes: 1

Related Questions