Search code examples
cakephpcakephp-3.x

CakePHP 3 How keep value and key fields same in select options?


I have a array like

<?php $words = ['a','b','c'] ?>

After try cakephp code

<?= $this->Form->select('word', $words) ?>

My select box is looking like

<select name="word">
    <option value="0">a</option>
    <option value="1">b</option>
    <option value="2">c</option>
</select>

How can I get my output like

<select name="word">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

Solution

  • The form helper will use the array keys as the option element values, so you fix the problem by passing an array where the keys have the values that you desire.

    For example use array_combine() to create a new array using the existing array's values as keys:

    $words = array_combine($words, $words);
    

    See also