php – PHP Remove “Empty” Values in Array

php

I'm trying to clean an array from empty values by using the following function:

function remove_empty_cells($data)
{
    $findthis = array("/\r\n/u", "/\n/u", "/\r/u", "/\s+/u", "~\x{00a0}~");
    for($i=0; $i<count($data); $i++)
    {
        $data[$i] = preg_replace($findthis, " ", $data[$i]);
        $data[$i] = htmlspecialchars_decode(htmlspecialchars($data[$i], ENT_SUBSTITUTE, 'UTF-8'));
        if (empty($data[$i]) ||
            mb_strlen($data[$i]) < strlen($data[$i]) ||
            is_null($data[$i]) ||
            $data[$i] = " " ||
            $data[$i] = "" ||
            $data[$i] == "0")
        {
             array_splice($data, $i, 1);
        };//end if
    };//end for
    return $data;
};//end func

The empty values don't go away, I fail to identify them..

the data:

array (
  0 => '
',
  1 => 'BEGIN:VCARD 
',
  2 => '
',
  3 => '
',
  4 => '
',
  5 => '
',
  6 => '
',
  7 => 'VERSION:2.1 
',


might be some encoding problem or something.. it doesnt look like multibyte characters..
the result i get is:

array (
  0 => 'BEGIN:VCARD 
',
  1 => '
',
  2 => '
',
  3 => 'VERSION:2.1 
',

Best Answer

You can use the PHP function array_filter() to remove the empty values

<?php
$array = array("sampe1", "", "sample2", null, "sample4", "rajesh", "suresh", "test", "");
var_dump($array);
echo "<hr/>";
$result = array_filter($array);                 
var_dump($result);
?>

This will print out:

array(9) { [0]=> string(6) "sampe1" [1]=> string(0) "" [2]=> string(7) "sample2" [3]=> NULL [4]=> string(7) "sample4" [5]=> string(6) "rajesh" [6]=> string(6) "suresh" [7]=> string(4) "test" [8]=> string(0) "" }

array(6) { [0]=> string(6) "sampe1" [2]=> string(7) "sample2" [4]=> string(7) "sample4" [5]=> string(6) "rajesh" [6]=> string(6) "suresh" [7]=> string(4) "test" 
Related Question