title: Selecting a random element from a PHP associative array
body: <p>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:</p>
  
  <p>Initialize.</p>
  
  <pre><code>$locations = array();
  </code></pre>
  
  <p>Loops through a SQL query and adds key/val pairs:</p>
  
  <pre><code>array_push($locations, "'$location_id' =&gt; '$location_name'");
  </code></pre>
  
  <p>Later on, I select a random index of the array:</p>
  
  <pre><code>$rand = array_rand($locations);
  </code></pre>
  
  <p>Rand is just a number. So locations[$rand] gives me something like:</p>
  
  <pre><code>'1' =&gt; 'Location 1'
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>foreach($locations[$rand] as $loc_id =&gt; $location_name) { 
      echo "$key : $value&lt;br/&gt;\n";
  }
  
  $loc_id, $location_name = each($locations[$rand]);
  
  $location_name = $locations[key($rand)];
  </code></pre>
  
  <p>None of these 3 attempts work. They all throw errors like "Passed variable is not an array".</p>
  
  <p>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.</p>