Code snippet to create an associative array of numbers with a blank for the #options parameter in the Form API

I kept banging my head against this one because the PHP function array_merge() will act strangely if all of the keys in an associate array are integers. So doing the following DOES NOT WORK:

'#options' => array_merge(array('' => ''), drupal_map_assoc(range(1, 100))),

But, doing the following DOES:

'#options' => array('' => '') + drupal_map_assoc(range(1, 100)),

Another solution that works, but is not as concise:

'#options' => drupal_map_assoc(array_merge(array('' => ''), range(1, 100)));


Comments

'#options' => array('' => '') + drupal_map_assoc(range(1, 100)),
The plus operator for arrays is similar to array_merge, but different in important (read: confusing) ways.

With +, the keys from the first array will not be overwritten if the same keys exist in the second array. So array('cats' => 'good') + array('cats' => 'bad') will still return array('cats' => 'good').

Besides that, + won't re-key your numeric values, and, of course, new values from the second array will be appended to the end. So starting the operation with "array('' => '') + ..." will ensure that the blank key remains at the start.

Thanks, Kevin, I like that much better, and updated the post to reflect. Cheers!

Thanks for the tip!

Please update the title to '#options' instead of '#option'.

Thanks Randy, that should go live in a few minutes. :)