user7949182
user7949182

Reputation:

PHP - how to randomly get something from array

how can i get something randomly from a array for example i have this array I want to grab one of those lines randomly how can I do that using PHP?

 $quizes = array(
        '3-1' => '2',
        '4+4' => '8',
        '7-5' => '2',
        '4+2' => '6',
        '9-3' => '6',
        '1+2' => '3',
        '9+9' => '18',
        '3+2' => '5',
        '2*3' => '6',
        '5*3' => '15',
        '6+6' => '12',
        '3+4' => '7',
        '7-4' => '3',
        '6+2' => '8',
        '3*2' => '6',
        '7+6' => '13',
        '1+1' => '2',
        '4*4' => '16',
        '10-3' => '7'
    );

What i have tried

$rand_keys = array_rand($quizes, 2);
echo $quizes[$rand_keys[0]] . "\n";
echo $quizes[$rand_keys[1]] . "\n";

but this only returns results such as 2 7, 15 2, 3 2 and more

Please help thank you

Upvotes: 0

Views: 24

Answers (3)

Don't Panic
Don't Panic

Reputation: 41810

Each of the "rows" in your code is actually two parts: a key and its corresponding value. For example, in the first row '3-1' is the key and '2' is its value. The => operator indicates this relationship.

The array_rand function you used will return a random key (or set of keys, if you specify the second parameter) from your array.

$key = array_rand($quizes);    // returns a random key e.g. '3-1'

Then you can use that key to get the corresponding value,

$value = $quizes[$key];        // returns the value that matches $key

There are various ways to output them from that point. If you want it to look kind of like it does in the code, you can use

echo "$key => $value";

Upvotes: 0

Dominik Szymański
Dominik Szymański

Reputation: 822

Well, you are getting exactly what you are asking for - value that belongs to randomly chosen key. To get key => value pair execute:

echo $rand_keys[0] . " => " . $quizes[$rand_keys[0]] . "\n";

Of course you can format output however you'd like to.

Upvotes: 0

caylee
caylee

Reputation: 941

You can randomize the array order and take the first element. The code would look like this:

shuffle($quizes);

Upvotes: 1

Related Questions