user3753641
user3753641

Reputation: 29

PHP rand explanation using an array?

I have very little programming experience but I am going over a php book and this block of code is confusing me.

If rand generates a random integer, how does this program use ABCDEFG in the array. Can you please explain the program thank you. I know what the result is, I am just not sure how it get it.

<?php

$array = '123456789ABCDEFG';

$s = '';

    for ($i=1; $i < 50; $i++) { 
        $s.= $array[rand(0,strlen($array)-1)]; //explain please

}

echo $s;

?>

Upvotes: 1

Views: 82

Answers (3)

SeanCannon
SeanCannon

Reputation: 77956

It's using the array index so $array[11] would equal 'C'. rand() takes a range - in your example that's from 0 to strlen($array)-1 which is the length of the string, minus 1 since it's a 0 based index.

Upvotes: 5

Marc B
Marc B

Reputation: 360572

Break it down into parts:

strlen($array) - returns the length of the string in $array, which would be 17
strlen($array) - 1  => 16

rand(0, 16) - generate a random number between 0 and 16

$array[$random_number] - get the $random_number'th element of the array

Upvotes: 2

The_DemoCorgin
The_DemoCorgin

Reputation: 744

Its just taking the length of the array with strlen($array). It doesn't matter what is in the string just the length. Then its generating a random number between 0 and the length of the string minus one.

Then it takes whatever character is in that position in the array (so $array[5] would be '6', $array[12] would be 'C', etc) and appending that to string $s. It then has a for loop to repeat it 50 times.

What you end up with is a random string that is 50 characters long and contains the numbers 1-9 and letters A-G.

Upvotes: 0

Related Questions