Incorrect count of $_FILE fields

Asked

Viewed 29 times

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[]" />

By sending 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 me 03 fields, however, if I select two fields still appear count 03.

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

  • The form sends the field, but empty. You would have to count the ones that are set

  • 1

    count(array_filter($_FILES['imagem']['tmp_name'])) probably already emilinará all null values.

  • Perfect @Andersoncarloswoss, that’s exactly what I needed. :)

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 it is necessary to fill it out, leaving it for the developer to validate. If in your case the field can be blank, just use the function array_filter to eliminate null values:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.