2

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!

Anton
  • 23
  • 2
  • 1
    [`array_map`](http://php.net/array_map) can do just that. – mario Feb 21 '19 at 21:33
  • 1
    That code doesn't look like it actually works the way you think it does. Do a var_dump($_FILES) and see what it contains. – gview Feb 21 '19 at 21:36
  • You most certainly can manipulate an entire array with one function. array_map() and array_walk() are two possible options. – benjaminhull Feb 21 '19 at 21:42
  • INTeresting. I just did the var_dump and it looks like the file type information is already in there so I don't even need to do this. But thanks for the replies guys, this is exactly what I need. – Anton Feb 21 '19 at 21:45
  • Generally if you need to do the same thing to every member of an array, a foreach loop is cleaner and more reliable than a for loop. – Don't Panic Feb 21 '19 at 22:06

1 Answers1

1

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);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87