0

If i have an array such as

[Yellow] => 1 [Red] => 2 [Blue] => 3

and then want to use these in a form INPUT with $options to make a dropdown selection, is it possible to use the color names Yellow/Red/Blue instead of the values 1/2/3?

currently the dropdown has 1, 2, 3 as the options instead of the names. The array is used elsewhere and is in the format for a reason.

1 Answer 1

1

You could use the array_flip method to swap the keys and values around

$array = array('Yellow' => 1, 'Red' => 2, 'Blue' => 3);

$flippedArray = array_flip($array);

// => [1] => 'Yellow', [2] => 'Red', [3] => 'Blue'

Then use the flippedArray as the options in your select element with the form helper

echo $this->Form->select('colours', $flippedArray);

Or you could combine the colours into a new array for the select element

$combinedArray = array_combine(array_keys($array), array_keys($array));

//=> [Yellow] => 'Yellow', [Red] => 'Red', [Blue] => 'Blue'

echo $this->Form->select('colours', $combinedArray);

In this way you could then use the value passed back from your form as the key of your orignal array if you needed to

Sign up to request clarification or add additional context in comments.

1 Comment

that is awesome, thanks for the options, that second one will work a treat!.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.