Prepending an empty string key option to options array for form_dropdown function in CodeIgniter 4
Created:04 Feb 2022 00:47:56 , in Web development
A couple of sentences on how to prepend an options array, which contains numerical keys with a non-numerical key option for form_dropdown function in CodeIgniter 4. The option could be something like, '' => 'Choose ...' . One very good, probably the best, solution to this problem is just insert this non-numerical key option as the first item before all the other options array items are added to the array. However, if for some reason it can't be done before the options array is in a view and ready for consumption, below is one way to proceed:
If your options array looks similar to this:
$options = [ '5' => '2018', '13' => '2017', . . . ];
and you want it to look like this before form_dropdown() processes it:
$options = [ '' => 'Choose ...' '5' => '2018', '13' => '2017', . . . ];
You might want to do this:
$options[''] = 'Choose ...'; ksort($options); echo form_dropdown( 'posts', $options, [''] );
The first argument to form_dropdown() is used by the function to create a HTML form field name (e.g. name=posts). The second argument is a list of options. In this case it is the supplemented list of options. The third argument specifies, which option should be selected by default, in this case it is the first options. As a reminder, ksort() sorts array items by key.
At the first glance, you might think it is probably better to use something like array_combine() to add the extra option. The trouble is, the function rewrites numerical array keys, so instead of '',5,13, resulting array keys are going to be 0,1,2 - not quite the expected result.
This post was updated on 04 Feb 2022 00:58:49
Author, Copyright and citation
Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.
©Copyright, 2022 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.
Computer code, if present in the article, is excluded from the above and licensed under GPLv3.
Cite this article as:
Wojnowski, Sylwester. "Prepending an empty string key option to options array for form_dropdown function in CodeIgniter 4." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/prepending-an-empty-string-key-option-to-options-array-for-formdropdown-function-in-codeigniter-4