How to get the total number of iterations in a foreach
There may be a better way of doing this and I'm certainly open to suggestions.
I have a file upload script that will handle multiple uploads. What I want to do is count the number of iterations that the loop makes for each file that was successfully moved and if that number equals the total number of files uploaded, then use an exception to show the user that the f开发者_Go百科iles were received.
I thought that I would increment inside the loop then count from there but what I am getting is an array for each file that is uploaded which results in an incorrect total. Is there a better way to do this or successfully count each iteration?
This is the structure I have to work with
foreach($files as $file)
{
if ($file['error'] == UPLOAD_ERR_OK)
{
move_uploaded_file($file['tmp_name'], $filename);
}
else
{
//error
}
}
You pretty much have to do it with a counter.
$success = 0;
foreach($_FILES as $file) {
if(is_uploaded_file($file['tmp_name'])) {
move_uploaded_file($file['tmp_name'], $destination);
$success += 1;
}
}
if($success != count($_FILES)) {
//error message / exception
}
Edit - You can set an error flag, or flags in your error handling... but there's not really a way to do this that is insanely better.
foreach($files as $file)
{
if ($file['error'] == UPLOAD_ERR_OK)
{
move_uploaded_file($file['tmp_name'], $filename);
}
else
{
//error
$upload_errors += 1;
//or, to get a little more info...
//$upload_errors[] = $file
}
}
if( $upload_errors == 0) { //or count($upload_errors) == 0
// tell the user that the upload failed.
}
foreach ($array as &$item)
You can just do count($array)
Just throwing this out there since you know the number of files how but just using a for loop. with two counters one for the loop and one for successes, and unless your script fails mostly ( and you want to not how unusual it is that everything worked) don't throw an exception if everything works.
Here you can see that you can use count($_FILES) to count the number of uploaded files. Mind you, this is not the number of correctly uploaded files.
<?php
if (isset($_FILES) && !empty($_FILES)) {
echo count($_FILES).' files were uploaded<br>';
?><pre><?php
print_r($_FILES);
?></pre><?php
}
?>
<form
action="<?php echo $_SERVER['PHP_SELF'];?>"
method="post"
enctype="multipart/form-data"
>
File 1<input type="file" name="file1"><br>
File 2<input type="file" name="file2"><br>
File 3<input type="file" name="file3"><br>
<input type="submit" value="upload">
</form>
精彩评论