27

I've got an associative array in PHP and want to select a random key/value pair out of it. Here's what I have so far:

Initialize.

$locations = array();

Loops through a SQL query and adds key/val pairs:

array_push($locations, "'$location_id' => '$location_name'");

Later on, I select a random index of the array:

$rand = array_rand($locations);

Rand is just a number. So locations[$rand] gives me something like:

'1' => 'Location 1'

OK great, an assoc array element. At this point, I do not know the key of this assoc array, so I've tried the following things:

foreach($locations[$rand] as $loc_id => $location_name) { 
    echo "$key : $value<br/>\n";
}

$loc_id, $location_name = each($locations[$rand]);

$location_name = $locations[key($rand)];

None of these 3 attempts work. They all throw errors like "Passed variable is not an array".

I'm sure there's some simple 1 liner that can pluck a random key/value pair from the array. Or my syntax is off. I'd really appreciate the help.

3 Answers 3

43
$array = array('a' => 1, 'b' => 2);
$key = array_rand($array);
$value = $array[$key];

Your problem is in array_push($locations, "'$location_id' => '$location_name'");. Do this instead: $locations[$location_id] = $location_name;. Then array_rand($location) will return a random $location_id; and you can get the name with $name = $locations[$location_id].

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

2 Comments

Your problem is in array_push($locations, "'$location_id' => '$location_name'");. Do this instead: $locations[$location_id] = $location_name;. Then array_rand($location) will return a random $location_id; and you can get the name with $name = $locations[$location_id].
you're all correct, of course - i just picked this one bc i work best with example code. and yeah, i'm pretty embarrassed about the push not being correct. i code a ton in perl (w hashes) so i should have known better! THANK YOU!
6

array_rand() returns a key from the array, not a value. You can just use:

$location_name = $locations[$rand];

To get the location name.


Here's a full example: http://codepad.org/zR2YdMGN

Just click submit a few times, you'll see the random working.

3 Comments

This still doesn't give the key.
Ok, sorry. Then the claim ($rand is just a number) from the OP is wrong. And I was foolish enough to not verify this claim.
@M_rk It returns the key :) I updated my answer so that it has a link to the PHP Man page for array_rand
1

You can do it with one line:


$randomValue = array_rand(array_flip(['value_1', 'value_2']))

You will get the value right away instead of the key.

Comments

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.