Jump to content

[SOLVED] array_rand function


ironman32

Recommended Posts

I've been using the array_rand function based on this example

<?php
srand((float) microtime() * 10000000);
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

 

I just wanted to know what this part of the code meant

 $input[$rand_keys[0]] .;

 

Would anyone be able to explain it to me please?

Link to comment
https://forums.phpfreaks.com/topic/152304-solved-array_rand-function/
Share on other sites

Return Values

 

If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

$rand_keys was created from array_rand, and as the script requested 2 returns it returns them as an array

ie

$rand_keys[0] = 2

$rand_keys[1] = 4

the values are the index values

so

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");

is infact

$input[0] = "Neo";

$input[1] = "Morpheus";

$input[2] = "Trinity";

$input[3] = "Cypher";

$input[4] = "Tank";

 

Now the 2 returns were 2 and 4

So you can now see it refers to

$input[2] = "Trinity"; & $input[4] = "Tank";

 

 

i hope that clears it up

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.