1
Array ( [0] => '1/1/2014' 
[1] => 'abx pp' 
[2] => '' 
[3] => '' 
[4] => '<31-12-2013>' 
[5] => '' 
[6] => '' 
[7] => '555017081788' 
[8] => '' 
[9] => '' 
[10] => ''
 [11] => '1/1/2014' 
[12] => '' 
[13] => '' 
[14] => '' 
[15] => ''
 [16] => '81,072.60' ) 

I need to filter above array as below

Array (
 [0] => '1/1/2014' 
[1] => 'abx pp'  
[4] => '<31-12-2013>'
[7] => '555017081788' 
[11] => '1/1/2014'
[16] => '81,072.60' ) 

I tried with loops and seems to be slow What is the best way?

  • I wonder why everybody has missed the easiest solution: `$arr = array_diff($arr, (array)"''");`. –  Jan 11 '14 at 07:03

5 Answers5

2

Two simple methods. First, use php function array_filter. Note that for array_filter function second parameter(callback function) is not required:

print_r(array_filter($yourArray);

Second, using loop:

foreach($yourArrayas $key => $val;) 
{ 
    if($val== '') 
    { 
        unset($yourArrayas [$key]); 
    } 
} 
print_r($linksArray); 
sergio
  • 5,210
  • 7
  • 24
  • 46
1

Take a look at the array_filter() function.

Alireza Fallah
  • 4,609
  • 3
  • 31
  • 57
awei
  • 1,154
  • 10
  • 26
0

You can use array_filter function Please check below Remove empty array elements and http://in2.php.net/array_filter

but i am not sure it is fast or not.

Community
  • 1
  • 1
nitin jain
  • 298
  • 6
  • 19
  • That's really a jerk comment considering what rep he is... It takes 50 rep to comment globally. The only thing he can actually say is the answer field. – Sparatan117 Jan 11 '14 at 07:45
0

According to documentation of php manual linked below :

converting to boolean

'' equals to false , AND this :

print_r(array_filter($entry));

will perfectly work ( tested ).

And there is no need to write a function to filter quotes .

Samira Khorshidi
  • 963
  • 1
  • 9
  • 29
0

You could also expand this solution to include regexp for more powerful checks on array items.

array_filter($array, "removeEmptyArrayItems");

function removeEmptyArrayItems($arrayItem)
{
    if($arrayItem == '')
    {
        return false;
    } else
        return true;
}

OR

foreach($array as $arrayItem)
{
    if($arrayItem == '')
    {
        unset($arrayItem);
    }
}

The loop on this should not be slow, to remove these you have to loop through and check each value, that is just how it works.

Heath N
  • 533
  • 1
  • 5
  • 13