It happens to have lists in the comma separated format, like 1, 2, 3 or banana, apple, peach. While coding, you may need to loop through those values and have them as an array to make things easier.
WordPress has two useful functions you can use to avoid writing them on your own: wp_parse_list()
and wp_parse_id_list()
.
wp_parse_list()
accepts a string and returns an array. If you provide an array, the function is smart enough to just return it, so you can use it without caring if your variable is or is not an array.
The wp_parse_list()
function split by comma and space, removes the empty items and filters items that are not scalar (when the provided value is already an array).
The more specialised wp_parse_id_list()
ensures the returned array is made of positive integers, usually representing IDs of database records. And removes all the duplicates.
Another useful function is wp_parse_slug_list()
that returns a “title” sanitised array of strings, always unique.
WordPress provides lots of basic functions, it is worth to explore them and saving some lines of code!