phparraysfunctionpostdata

PHP - Is there a way to run array values through string/filesystem functions without a for loop?


I'm still a little green so please forgive me if there's an obvious answer to this question. Basically, I'm wondering if there's a better, more abbreviated way, to do- this:

$file_ext = array();
$cust_file = $_FILES["cust_file"]["name"];

for ($i = 0; $i <= 4; $i++) {
    $cust_img_type = strtolower(pathinfo($cust_file[$i],PATHINFO_EXTENSION));
    array_push($file_ext,$cust_img_type);
    }

I have searched for an answer and as far as I can tell you simply can't just transform an entire array with a function like you can with single variables. Can anyone confirm/deny? I feel like that's a lot of code just to pull the file extension out an array of post data.

Thanks!


Solution

  • Just map each element of the array to a function:

    $file_ext = array_map(function($v) {
                              return strtolower(pathinfo($v, PATHINFO_EXTENSION));
                          }, $cust_file);
    

    When you don't need arguments to the function it is simpler:

    $file_ext = array_map('strtolower', $cust_file);