vep temp
vep temp

Reputation: 267

use array for loops

//array of image file types
    $fileType_array = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);

    //getimagesize to determine the file_type of the image
    $getImage_thumbnail = getimagesize($_FILES[$thumbnail_fieldname]['tmp_name']);
        $getImage_thumbnail_type = $getImage_thumbnail[2];
    $getImage_desktop_1280x800 = getimagesize($_FILES[$desktop_fieldname_1280x800]['tmp_name']);
        $getImage_desktop_1280x800 = $getImage_desktop_1280x800[2];
    $getImage_desktop_1366x768 = getimagesize($_FILES[$desktop_fieldname_1366x768]['tmp_name']);
        $getImage_desktop_1366x768 = $getImage_desktop_1366x768[2];
    $getImage_desktop_1920x1080 = getimagesize($_FILES[$desktop_fieldname_1920x1080]['tmp_name']);
        $getImage_desktop_1920x800 = $getImage_desktop_1920x1080[2];

    if(in_array($getImage_thumbnail_type, $fileType_array, TRUE)){
        echo "<p>Thumbnail is an image.</p>";
        }

Above is my code to check if the files selected to upload are images, what I would like to do is use in_array just once not several if statements/in_array to check if the file type exists in the array. How can that be?

Upvotes: 0

Views: 38

Answers (1)

kero
kero

Reputation: 10638

You will need to check all this values. But the task can be simplified by working with an array.

$fileType_array = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);

$filenames = array($thumbnail_fieldname, $desktop_fieldname_1280x800, ...);
$files = array();
foreach ($filenames as $filename) {
    if (isset($_FILES[$filename]['tmp_name'])) {
        $resource = getimagesize($_FILES[$filename]['tmp_name']);
        $type = $resource[2];
        if (in_array($type, $fileType_array, TRUE)) {
            $files[$filename] = $resource;
        }
    }
}

This way only files with accepted filetypes will be stored in $files and when you want to change which files you are working with, you only need to update $filenames.

Upvotes: 1

Related Questions