8

Let's say I have a form like this:

<form action="upload.php" method="post" enctype="multipart/form-data">
File 1 : <input type="file" name="file[]" />
File 2 : <input type="file" name="file[]" />
<input type="submit" name="submit" value="Upload" />
</form>

I want to make sure that each file had upload file.
Here is my condition and the code that I write:

File 1 empty:

if(empty($_FILES['file']['name'][0]))
{
    echo 'file 1 empty';
}

File 2 empty:

if(empty($_FILES['file']['name'][1]))
{
    echo 'file 2 empty';
}

File 1 and File 2 empty:

if(empty($_FILES['file']['name'][0]) && ($_FILES['file']['name'][1]))
{
     echo 'file 1 and file 2 empty';
}

Is it possible to write the above condition in for loop? Or just seperately write the code is enough?

1
  • Yes, you can do it with a for or while loop, but if you are always dealing with only 2 files and you also need to know if both files are empty, what you have is pretty efficient. If you are dealing with a more complex situations with multiple files, then rewriting it as a loop is probably better. Commented Nov 29, 2015 at 3:30

1 Answer 1

11

use foreach

$i=1
foreach($_FILES['file']['name'] as $file){
if(empty($file))
{
    echo "file $i empty";
    $i++
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.