Search code examples
phpdrupal-6

Unset blank array items on the fly


I have an array which is being built using:

$features_data[$i] = preg_split("/\n/", $row);

The output is as follows:

Array
(
    [0] => Array
        (
            [0] =>   
            [1] =>   
            [2] =>                 <img src="http://example.com/sites/test/files/imagecache/feature-image/testimage_0.jpg" alt="" title=""  class="imagecache imagecache-feature-image imagecache-default imagecache-feature-image_default" width="654" height="260" />      
            [3] => 
            [4] =>   
            [5] =>   
            [6] =>                 Test 1      
            [7] => 
            [8] =>   
            [9] =>   
            [10] =>                 Lorem ipsum dolor sit...      
            [11] => 
            [12] => 
        )
    [1] => Array
        (
            [0] =>   
            [1] =>   
            [2] =>                       
            [3] => 
            [4] =>   
            [5] =>   
            [6] =>                 Test 2      
            [7] => 
            [8] =>   
            [9] =>   
            [10] =>                 Aenean id tellus nec...      
            [11] => 
            [12] => 
        )
    [2] => Array
        (
            [0] =>   
            [1] =>   
            [2] =>                       
            [3] => 
            [4] =>   
            [5] =>   
            [6] =>                 Test 3      
            [7] => 
            [8] =>   
            [9] =>   
            [10] =>                 Maecenas ut pharetra...      
            [11] => 
            [12] => 
        )
)

I'd like to get rid of the blank array items and then reset the array counter. I've tried using php unset but for some reason it's not working. Any help would be greatly appreciated.


Solution

  • You could use array_filter() but what you really want to use is PREG_SPLIT_NO_EMPTY instead.

    preg_split("/\n/", $row, -1, PREG_SPLIT_NO_EMPTY)
    

    Edit: of course it entirely depends on your output. Your pattern should probably be something like this

    preg_split("/[\\n\\r \\t]+/", $row, -1, PREG_SPLIT_NO_EMPTY)
    

    or this

    preg_split("/[\\n\\r \\t]*\\n[\\n\\r \\t]*/", $row, -1, PREG_SPLIT_NO_EMPTY)