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
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.

Link to comment
Share on other sites

$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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.