3

I'm getting the following array when I upload array of files.

array(1) { 
    ["upload"]=>array(2) { 
        ["name"]=>array(2) { 
            [0]=>string(9)"file0.txt" 
            [1]=>string(9)"file1.txt" 
        } 
        ["type"]=>array(2) { 
            [0]=>string(10)"text/plain" 
            [1]=>string(10)"text/html" 
        } 
        ...
    } 
} 

What is reason (technical reason or any benefits) behind the array received in the above format instead of the following ?

array(1) { 
    ["upload"]=>array(2) { 
        [0]=>array(2) { 
            ["name"]=>string(9)"file0.txt" 
            ["type"]=>string(10)"text/plain" 
            ...
        }, 
        [1]=>array(2) { 
            ["name"]=>string(9)"file1.txt" 
            ["type"]=>string(10)"text/html" 
            ...
        } 
    } 
} 
2

1 Answer 1

3

I think this is the basic way of how $_FILES provides array now if you want to convert that into the formate you specified i found the code form the link

A nice trick to reorder the $_FILES array when you use a input name as array is:

<?php 
    function diverse_array($vector) { 
        $result = array(); 
        foreach($vector as $key1 => $value1) 
            foreach($value1 as $key2 => $value2) 
                $result[$key2][$key1] = $value2; 
                return $result; 
    } 
?> 

will transform this:

array(1) { 
    ["upload"]=>array(2) { 
        ["name"]=>array(2) { 
            [0]=>string(9)"file0.txt" 
            [1]=>string(9)"file1.txt" 
        } 
        ["type"]=>array(2) { 
            [0]=>string(10)"text/plain" 
            [1]=>string(10)"text/html" 
        } 
    } 
} 

into:

array(1) { 
    ["upload"]=>array(2) { 
        [0]=>array(2) { 
            ["name"]=>string(9)"file0.txt" 
            ["type"]=>string(10)"text/plain" 
        }, 
        [1]=>array(2) { 
            ["name"]=>string(9)"file1.txt" 
            ["type"]=>string(10)"text/html" 
        } 
    } 
} 

just do:

<?php $upload = diverse_array($_FILES["upload"]); ?>
1
  • Thank you for your reply and I appreciate it. I was looking the benefits or the reason behind this pattern. Because of this pattern many programmers have to diverse this array eg: framework.zend.com/manual/2.2/en/modules/… Code in my question is taken from the same php page you mentioned :-)
    – nithinTa
    Dec 8, 2017 at 6:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.