Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the total number of iterations in a foreach

Tags:

php

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 files 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
        }
    }
like image 398
Timmay Avatar asked Oct 25 '22 21:10

Timmay


1 Answers

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.
}
like image 80
davethegr8 Avatar answered Nov 14 '22 10:11

davethegr8