-1

Suppose I have a PHP array of file names like $f = [ 'file1.jpg', file2.png', 'file3.bmp', 'file4.zip', 'file5.txt'... ];

Now how do I remove all the files from the array with not allowed extension, in this case remove everything except .jpg and .png ?

StudentX
  • 2,243
  • 6
  • 35
  • 67

1 Answers1

1

try this code, you can add mode allowed extensions in $allowed array, but without dot

$f = array('file1.jpg', 'file2.png', 'file3.bmp', 'file4.zip', 'file5.txt' );
$allowed = array('jpg','png');

echo "<pre>before removing";
print_r($f);
echo "</pre>";

    foreach($f as $k=>$v){
        $ext = end(explode(".",$v));
        if(!in_array($ext,$allowed)){
            unset($f[$k]);
        }
    }

echo "<pre>after removing";
print_r($f);
echo "</pre>";
alamnaryab
  • 1,480
  • 3
  • 19
  • 31