user2816376
user2816376

Reputation: 125

How do I check to see if array slot is empty?

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

Answers (2)

Brad Christie
Brad Christie

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

Kermit
Kermit

Reputation: 34063

To ignore the empty values, you can use

$list = array_filter($list);

Results

Array
(
    [0] => first
    [1] => second
    [4] => fifth
    [5] => sixth
)

Source: Mark

Upvotes: 1

Related Questions