4

Possible Duplicate:
Remove empty array elements

I want to remove empty elements from an array. I have a string which is set to an array by explode(). Then I'm using array_filter() to remove the empty elements. But that does not work. See Code below:

$location = "http://www.bespike.com/Packages.gz";
$handle = fopen($location, "rb");
$source_code = stream_get_contents($handle);
$source_code = gzdecode($source_code);
$source_code = str_replace("\n", ":ben:", $source_code);
$list = explode(":ben:", $source_code);
print_r($list);

But it doesn't work, $list still has empty elements. I have also tried doing it with the empty() function but the outcome is the same.

Community
  • 1
  • 1
Benji Wilson
  • 45
  • 1
  • 5

3 Answers3

8

If the file has \r\n as a carriage return, as that one does, splitting with \n will get you an element which appears empty but is not -- it contains a \r.

$source_code = gzdecode($source_code);
$list = array_filter(explode("\r\n", $source_code));
print_r($list);

You may also try with your existing code, replacing "\r\n" instead of "\n" (you still need an array_filter somewhere).

A perhaps slower but more flexible option employs preg_split and the special regex metacharacter \R which matches any newline, both Unix and Windows:

$source_code = gzdecode($source_code);
$list = array_filter(preg_split('#\\R#', $source_code));
print_r($list);
LSerni
  • 53,899
  • 9
  • 63
  • 106
  • thank you for this, worked perfect thank you :) – Benji Wilson Jul 10 '12 at 18:17
  • @downvoter: is there a problem? Feel free to add a comment, or even ask a question [remember to specify clearly what the problem is - I only assume that the above doesn't work for you; that's not much for me to work on]. – LSerni Jun 23 '14 at 10:42
1
$arr = array('one', '', 'two');
$arr = array_filter($arr, 'strlen');

Note this does not reset keys. The above will leave you with an array of two keys - 0 and 2. If your array is indexed rather than associative you can fix this via

$arr = array_values($arr);

The keys will now be 0 and 1.

Mitya
  • 32,084
  • 8
  • 49
  • 92
0

This is what you need:

$list = array_filter($list, 'removeEmptyElements');

function removeEmptyElements($var)
{
  return trim($var) != "" ? $var : null;
}

If no callback is supplied, all entries of input equal to FALSE will be removed. But in your case you have an empty string with the lenght of 1 which is not FALSE. Thats why we need to supply the callback

Besnik
  • 6,254
  • 1
  • 29
  • 32