Hello.

I'm having difficulty getting the array_rand function to work. The example for the array_rand function in the PHP Manual calls two values. If I change the example to try to get only one variable it doesn't output anything.

http://us2.php.net/manual/en/function.array-rand.php

// This is the example in the PHP Manual
// It outputs two values
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2); // Tells it to output 2 values
echo $input[$rand_keys[0]] . "<br>\n";
echo $input[$rand_keys[1]] . "<br>\n";

// This should output one value but it doesn not output anything.
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 1); // Change this to one
echo $input[$rand_keys[0]] . "<br>\n";
echo $input[$rand_keys[1]] . "<br>\n";

Can anybody see what I'm doing wrong?

Thanks.

    Because, like the page says, [man]array_rand[/man] doesn't return an array of keys if it only has to return one key.

    error_reporting(E_ALL);
    $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
    $rand_keys = array_rand($input, 1); // Change this to one
    var_dump($rand_keys);
    echo $input[$rand_keys[0]] . "<br>\n";
    echo $input[$rand_keys[1]] . "<br>\n";  

      Weedpacket;

      It's supposed to work with only one value. The Manual says you can use the array_rand function if you want to "pick one or more random entries out of an array."

      It's got to be something simple I'm overlooking.

        Yes, you're overlooking the bit on the manual page that says

        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.

          Weekpacket;

          Thanks for helping me out. I got it figured out now.

          // This outputs the random value.
          $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
          $rand_keys = array_rand($input, 1);
          echo $input[$rand_keys];
          

          It was right there in front of me but I was overlooking it.

          Thanks again.

            Write a Reply...