On more than one occasion, I've found myself executing some PHP along the lines of this:
1<?php 2 3// Some user-generated array of input 4$input = [ ..., ]; 5 6foreach ($input as $field) { 7 if (trim($field) === '' ) { 8 continue; 9 }10 11 // Persist the value into the database12}
This has happened one time too many now, and seeing as pretty much all of my projects now are built on top of composer, adding a helpers.php
file into my project and autoloading it makes including a generic function to handle this really easy.
1/** 2 * Ensure that the input array has no empty-string values assigned. 3 * 4 * @param array $array 5 * 6 * @return array 7 */ 8function array_clean(array $array) 9{10 // Trim the array input values11 $array = array_map('trim', $array);12 13 // Filter any empty-string values out14 return array_filter($array, function ($item) {15 return $item !== '';16 });17}
Now, any time you need to work with a one-dimensional array that may have empty fields in it that you don't want to use, you can tidy up the earlier example a little bit:
1<?php2 3// Some user-generated array of input4$input = array_clean($request->input('user_input'));5 6foreach ($input as $field) {7 // Persist the value into the database, no longer worrying about saving empty values to the db8}