Thursday 9 June 2011

CakePHP Drop Down List - Same value for 'keys' and 'values'

By default, when we use the form helper to generate a [select] drop down list, the [value] of each [option] is the [id] of the particular table. However, we sometimes need to have [value] which is the same as the content of the [option], therefore we will need to use array_combine() function.

We can do in such a way:
 $array1=array_combine($array1, $array1)
$array1 is an array of data. The first parameter will go to be the [key] of the new array and the second parameter will go to be the [value] of the new array, thus making both the [key] and the [value] of the new array having the same value.

Let's said :
$array1(
[1] => a
[3] => b
[4] => c
)

After using the array_combine() function, the $array1 becomes:
$array1(
[a] => a
[b] => b
[c] => c
)

Reference:
1. FormHelper - Setting Option Value in Select Dropdown
2. php.net - array-combine

No comments: