1

So I have an associative array and I want to return 2 random values from it. This code only returns 1 array value, which is any of the 4 numbers at random.

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$key = array_rand($array); //array_rand($array,2); Putting 2 returns Illegal offset type
$value = $array[$key];
print_r($value); //prints a single random value (ex. 3)

How can I return 2 comma separated values from the array values only? Something like 3,4?

2

4 Answers 4

5

array_rand takes an additional optional parameter which specifies how many random entries you want out of the array.

$input_array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$rand_keys = array_rand($input_array, 2);
echo $input_array[$rand_keys[0]] . ',' . $input_array[$rand_keys[1]];

Check the PHP documentation for array_rand here.

Sign up to request clarification or add additional context in comments.

2 Comments

1. You have an extra parenthesis at the end of the 3rd line, and 2. This will only select 2 random keys, not the values from the original array.
@Jeshurun Thanks for the help:) But nickb posted first correctly, both very good answers!
1

Grab the keys from the array with array_keys(), shuffle the keys with shuffle(), and print out the values corresponding to the first two keys in the shuffled keys array, like so:

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$keys = array_keys( $array);
shuffle( $keys);
echo $array[ $keys[0] ] . ',' . $array[ $keys[1] ];

Demo

Or, you can use array_rand()'s second parameter to grab two keys, like so:

$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$keys = array_rand( $array, 2);
echo $array[ $keys[0] ] . ',' . $array[ $keys[1] ];

Demo

1 Comment

Going with this one as it was the quickest and works flawlessly!
0

There is a more efficient approach that preserves keys and values.

function shuffle_assoc(&$array) {
        $keys = array_keys($array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $array[$key];
        }

        $array = $new;

        return true;
    }

Check the documentation here

Comments

-1
$a=rand(0,sizeof($array));
$b=$a;
while ($a==$b) $b=rand(0,sizeof($array));

$ar=array_values($array);
$element1=$ar[$a];
$element2=$ar[$b];

Should be more efficient than shuffle() and freinds, if the array is large.

2 Comments

array_rand should be efficient, though.
Should be - I just didn't have it at hand!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.