Zend Form Element Select Helper

Posted by Tully on Wed 26 January 2011

Today I wrote a small helper that will transform an array to work with Zend Form Element Select.

Zend_Form_Element_Select uses the key of an array as the value, and the value as the key. I'm not sure why Zend did this, but I wrote a small helper class that can be used to re-arrange an array to work properly with the Zend Element Select.

To use the class, just give it the array, the key you would like to use as the name, and the key you'd like to use for the value.

Zend Form Helper

<?php
class Helpers_FormHelper {
    public static function createNewArrayWithGivenKeyValuePairs(Array $data, $key, $value) {
        $transformedData = array();
        foreach ($data as $row) {
            $transformedData[$row[$value]] = $row[$key]; 
        }   
        return $transformedData;
    }
}

Usage

<?php
Helpers_FormHelper::createNewArrayWithGivenKeyValuePairs($colors, 'name', 'id');

Array Before Helper

array
    0 => 
        array
        'id' => string '1' (length=1)
        'name' => string 'Red' (length=3)
    1 => 
        array
        'id' => string '2' (length=1)
        'name' => string 'Blue' (length=4)
    2 => 
        array
        'id' => string '3' (length=1)
        'name' => string 'Yellow' (length=6)
    3 => 
        array
        'id' => string '4' (length=1)
        'name' => string 'Orange' (length=6)
    4 => 
        array
        'id' => string '5' (length=1)
        'name' => string 'Green' (length=5)

Array After

array
    1 => string 'Red' (length=8)
    2 => string 'Blue' (length=7)
    3 => string 'Yellow' (length=7)
    4 => string 'Orange' (length=6)
    5 => string 'Green' (length=8)