0

My array is of following structure. It is a array of files submitted through form. I have multiple input fields for form. However if the user leave some field blank, the array will be displayed like below. I am then writing it to my database. I dont want the empty fields to be written.

I tried using array_filter() function, but it will not work since my array is not completely empty. The error element is set to 4. How do i do it?

Array
(
    [0] => Array
        (
            [name] => stock-photo-cup-icons-tea-and-coffee-raster-version-109119257.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpqWWM9X
            [error] => 0
            [size] => 30609
        )

    [1] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

    [2] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

    [3] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

)
prakashchhetri
  • 1,806
  • 4
  • 36
  • 61

4 Answers4

1

You can pass an (optional) callback to array_filter():

$filteredArray = array_filter($source, function($item) {
    return ($item['size'] > 0 && $item['error'] === 0);
});

var_dump($filteredArray);

Demo: http://codepad.viper-7.com/uocPT6

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
0

This simple script:

foreach ($array as &$a) {
    $todel = false;
    foreach ($a as $k => $v) {
        if (empty($v)) { // condition to consider a variable empty
            $todel = true; break;
        }
    }
    if ($todel) unset($a);
}

should work fine. I think that code pretty much explains itself. What we are doing is going in a foreach loop in $array (the main array) and checking if the $a subarrays (passed by reference) has any empty value. If so we are setting $todel = true (and break; for efficiency) that will unset the current $a sub array.

Shoe
  • 74,840
  • 36
  • 166
  • 272
0
for($i=0;$i<count($theArray);$i++)
{
    if($theArray[$i]['error']==4) 
    { 
        unset($theArray[$i]); 
    }
}

I would do it like that

Nic
  • 703
  • 8
  • 18
-1

Use a simple condition

if(error == 0){
    //insert here
}else{
   //do nothing
}
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103