Quick PHP tip: It is common to want to explode a string based on some delimiting character, then iterate over the array. Most of the time you don’t care about the empty items in the array. Suppose, for example, you have a dynamically constructed string of id numbers from a database or something and you want to iterate over them and do something. Here is a quick code sample to remove any entry that evaluates as false in the array.
$csvIdString = '1,2,3,,5,6,,8,'; $ids = array_filter(explode(',', $csvIdString)); print_r($ids); /* Result: Array ( [0] => 1 [1] => 2 [2] => 3 [4] => 5 [5] => 6 [7] => 8 ) */
Suppose you want to take a CSV string that might have some empty slots and clean it up.
$csvString = ',1,2,3,,5,6,,8,'; $string = implode(',', array_filter(explode(',', $csvString))); echo "String: $string"; /* Result: String: 1,2,3,5,6,8 */
Again, note that any array item that returns false will be removed. This includes 0, ” (empty strings), null, ‘false’, etc. The array_filter function can take a 2nd parameter for a callback function. This will let you do much more powerful decisioning on which items to remove from the array. Just have your callback return false for values you want to have removed.
Your examples above don’t work if you enter a space between or after any of the commas…
For example, try:
‘1,2,3,,5,6,,8, ‘
or
‘1,2,3, ,5,6,,8,’
Can a simple trim fix this problem? I thought your solution would help me, but that’s exactly what I had already tried. Basically, if the user inputs a space as the last value, that value is exploded into its own empty array value. I thought the trim function would solve this problem, but evidently I’m doing it wrong…
Keep in mind that you can provide your own callback function to handle more complex scenarios. Perhaps write a callback function that trims the values before evaluating them.