php, Web Development

Whipping some anonymous function in PHP

My goal is to validate a $_FILES array where uploaded file is an array of files. Due to the weird format of the $_FILES array for array version of the upload file, I have to validate each fields so that they must have the same node count per field. Anonymous function in PHP came handy for this scenario instead of creating a full function/class method.

Weird FILES format

Here is what the FILES array in PHP looks like when you upload it as an array.

Sample HTML:

<input type="file" name="attachments[]">
<input type="file" name="attachments[]">

The array format for $_FILES['attachments'] (taken from http://php.net/manual/en/features.file-upload.multiple.php):

Array
(
    [name] => Array
        (
            [0] => foo.txt
            [1] => bar.txt
        )

    [type] => Array
        (
            [0] => text/plain
            [1] => text/plain
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpYzdqkD
            [1] => /tmp/phpeEwEWG
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
        )

    [size] => Array
        (
            [0] => 123
            [1] => 456
        )
)

I wanted to make sure that each fields (name, type, etc) have the same count (in this case, they must have 2 values each).

I know there are better ways of doing this, but I just make it as an excuse to use anomynous functions in PHP.

Here is the code.

// Shortcut version
$values = $_FILES['attachments'];
$firstCount = count($values['name']);
$values = array_filter($values, function ($value) {
    return is_array($value) && count($value) === $firstCount;
});

// There are 5 expected fields
if (count($values) !== 5) {
    throw new \Exception('Invalid FILES array');
}

But the code above does not works! This is NOT JavaScript yo!

The anonymous/lambda function does not seem to see the firstCount variable. According to the documentation, we can fix that but adding the use ($foo) syntax within the lambda function to make it available inside the function.

// Shortcut version
$values = $_FILES['attachments'];
$firstCount = count($values['name']);
$values = array_filter($values, function ($value) use ($firstCount) {
    return is_array($value) && count($value) === $firstCount;
});

// There are 5 expected fields
if (count($values) !== 5) {
    throw new \Exception('Invalid FILES array');
}

That’s it!

Leave a reply

Your email address will not be published. Required fields are marked *