Incorrect count of $ _FILE fields

0

In the following structure:

<input type="file" id="imagem_01" name="imagem[]" />
<input type="file" id="imagem_02" name="imagem[]" />
<input type="file" id="imagem_03" name="imagem[]" />

When submitting I use this way:

echo count($_FILES['imagem']['tmp_name']) ;

Array
(
    [name] => Array
        (
            [0] => 1491629_701232416581971_1576042449_n.jpg
            [1] => 1798325_1420590811513009_1411268959_n.jpg
            [2] => 
        )
)

Returning 03 fields, however, if I select two fields yet count 03 appears.

My question is: How do I return the correct number of filled fields of the image type?

    
asked by anonymous 15.05.2017 / 15:54

1 answer

3

When you create the field in HTML, a null value will be sent to PHP, precisely because the field exists and sometimes needs to be filled in, leaving the developer to do the validation. If in your case the field can be blank, you only have to use the array_filter function to delete null values:

$tmpnames = array_filter($_FILES["imagem"]['tmp_name']);
echo count($tmpnames); // 2

This is because, when the second parameter of the function is not passed, PHP removes from the array all values that are parsed as false. Being an array of strings, all null values or empty string will be removed.

    
15.05.2017 / 16:12