Reputation: 125
In the example below $list is an array created by user input earlier in the code, and some slots the user has input nothing. I want to skip the empty items, so the commas aren't created in the output.
$list = array("first", "second", "", "", "fifth", "sixth", "", "");
foreach ($list as $each){$places .= $each . ",";}
results first,second,,,fifth,sixth,,,
result I want first,second,fifth,sixth
Got a solution. It looks like this:
$list = array_filter($list);
$places .= implode (",",$list);
Upvotes: 0
Views: 197
Reputation: 101614
array_filter
, when passed no second parameter, will remove any empty entries. From there you can proceed as normal:
foreach (array_filter($list) as $each){
$places .= $each . ',';
}
Though you can also use implode
if you're just turning it in to a CSV:
$places .= implode(',', array_filter($list));
Side Note Though in this case array_filter
may work, it is worth noting that this removes entries that result in a "falsy" result. That is to say:
$list = array_filter(array('foo','0','false',''));
// Result:
// array(2) {
// [0]=>
// string(3) "foo"
// [2]=>
// string(5) "false"
// }
So be careful. If the user could potentially be entering in numbers, I would stick with comparing empty
. Alternatively you can use the second parameter of array_filter
to make it more explicit:
function nonEmptyEntries($e)
{
return ((string)$e) !== '';
}
$list = array_filter($list, 'nonEmptyEntries');
// result:
//array(3) {
// [0]=>
// string(3) "foo"
// [1]=>
// string(1) "0"
// [2]=>
// string(5) "false"
//}
(Note that the 0
entry is kept, which differs from a blanket array_filter
)
Upvotes: 1