title: How to convert an array of arrays or objects to an associative array?
body: <p>I'm used to perl's map() function where the callback can assign both the key and the value, thus creating an associative array where the input was a flat array. I'm aware of <a href="http://www.php.net/manual/en/function.array-fill-keys.php"><code>array_fill_keys()</code></a> which can be useful if all you want to do is create a dictionary-style hash, but what if you don't necessarily want all values to be the same? Obviously all things can be done with foreach iteration, but what other (possibly more elegant) methods exist?</p>
  
  <p><strong>Edit</strong>: adding an example to clarify the transformation. Please don't get hung up on the transformation, the question is about transforming a flat list to a hash where we can't assume that all the values will be the same.</p>
  
  <pre><code>$original_array: ('a', 'b', 'c', 'd')
  $new_hash: ('a'=&gt;'yes', 'b'=&gt;'no', 'c'=&gt;'yes', 'd'=&gt;'no')
  
  *note: the values in this example are arbitrary, governed by some business logic that is not really relevant to this question. For example, perhaps it's based on the even-oddness of the ordinal value of the key
  </code></pre>
  
  <p><strong>Real-world Example</strong>
  So, using an answer that was provided here, here is how you could parse through the $_POST to get a list of only those input fields that match a given criteria. This could be useful, for example, if you have a lot of input fields in your form, but a certain group of them must be processed together.</p>
  
  <p>In this case I have a number of input fields that represent mappings to a database. Each of the input fields looks like this:
  <code>&lt;input name="field-user_email" value="2" /&gt;</code> where each of this type of field is prefixed with "field-".</p>
  
  <p>what we want to do is, first, get a list of only those input fields who actually start with "field-", then we want to create an associative array called <code>$mapped_fields</code> that has the extracted field name as the key and the actual input field's value as the value.</p>
  
  <pre><code>$mapped_fields = array_reduce( preg_grep( '/field-.+/', array_keys( $_POST ) ), function( $hash, $field ){ $hash[substr( $field, 6 )] = $_POST[$field]; return $hash; } );
  </code></pre>
  
  <p>Which outputs:</p>
  
  <pre><code>Array ( [date_of_birth] =&gt; 1 [user_email] =&gt; 2 [last_name] =&gt; 3 [first_name] =&gt; 4 [current_position] =&gt; 6 )
  </code></pre>
  
  <p>(So, just to forestall the naysayers, let me agree that this bit of compact code is arguably a lot less readable that a simple loop that iterates through $_POST and, for each key, checks to see if it has the prefix, and if so, pops it and its value onto an array)</p>