Download the PHP package flsouto/array2options without Composer
On this page you can find all versions of the php package flsouto/array2options. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package array2options
Installation
Install this library via composer:
array2options
This function allows you to easily build options from arrays for inserting into a "select" tag.
The above php code will produce the following html output:
Selecting an option
In the above html output the "Choose a Fruit" option will be selected by default since it is the first option inside the select element and no other option is marked as selected. But if for instance you wanted the 'orange' option to be selected, you could use the second parameter to the array2options function:
Notice the "selected" attribute in the following output:
Using associative arrays
While array2options is good for generating options when values are the same as their associated labels, sometimes we need to produce options whose values differ from their labels. This is where the assoc2options function comes in handy:
Output:
Notice: the assoc2options also allows you to set an option as "selected" just like array2option does.
Converting datasets to options
Usually you will be working with rows fetched from the database. In this case the data comes as data sets (AKA "array of arrays"). So, if you want to produce options for data in this format, you should use the dataset2options:
The above will produce as expected:
This function works by looking at the first attribute of each array, for determining the "value" of each option, and then looks at the second attribute for determing the "label". So it doesn't matter if your dataset contains more data besides just id and name of an object, as long as these attributes come in the first and second positions respectively.
Notice: the dataset2options also allows you to set an option as "selected" just like array2option and assoc2options do.
Final thoughts
Even though it is relatively simple to iterate over arrays and print out tags in your templates it makes your code ugly and is such a tedious work to do - especially when you have to include logic to select one of the options.
Why not generate the whole select widget?
I hear some complain that this library doesn't help build the entire "select" element. However, if you think about it, there is no difficulty in making the select tag. The somewhat "complexity" lies in the generation of the variable content that goes inside it. Besides, this way you can customize the select tag using plain html code without having to learn weird APIs. Learn and use an API that does something useful, not one that reinvents the wheel.