I want to output several elements of the array into a string separated by commas, but the last one is output since the forech loop processes everything so please help me output everything one by one

if(isset($_FILES)) { //пролистываем весь массив изображений по одному $_FILES['file']['name'] as $k=>$v $error = array(); foreach($_FILES['file']['name'] as $k=>$v){ $uploaddir = 'images/'; $uploadfile = $uploaddir.basename($_FILES['file']['name'][$k]); $comma_separated = implode(",", $uploadfilee); // Копируем файл из каталога для временного хранения файлов: if (!copy($_FILES['file']['tmp_name'][$k], $uploadfile)) { $error[] = "<div class='dannye'><h3>Ошибка! Не удалось загрузить файл на сервер!</div></h3>"; } } print_r($comma_separated); } 

    2 answers 2

    + You have a typo in the string

     $comma_separated = implode(",", $uploadfilee); 

    the $uploadfilee variable is not defined and $uploadfile not an array.

    • move_uploaded_file is used to move downloaded files
    • To check for errors in the $_FILES there is an error key. With a successful download, it is equal to UPLOAD_ERR_OK

    The final code will look something like this.

     $success_list = []; $error_list = []; $uploads_dir = __DIR__ . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR; foreach ($_FILES['pictures']['error'] as $key => $error) { if ($error == UPLOAD_ERR_OK) { $tmp_name = $_FILES["pictures"]["tmp_name"][$key]; $name = basename($_FILES["pictures"]["name"][$key]); $success = move_uploaded_file($tmp_name, "$uploads_dir/$name"); if ($success) { $success_list[] = $name; } else { $error_list[] = $name; } } else { $error_list[] = $_FILES['file']['name'][$key]; } } $error_list = implode(',', $error_list); $success_list = implode(',', $success_list); 
    • Thanks, everything works, just can you please explain a couple of lines $ tmp_name = $ _FILES ["pictures"] ["tmp_name"] [$ key]; and this $ error_list [] = $ _FILES ['file'] ['name'] [$ key]; thanks - Koly
    • @Koly first - getting the name of the temporary file, and the second - adding elements to the array (list with errors) - Maxim Timakov

    You have the key in the wrong place and the wrong variable in the loop, and the key in the loop is also not needed in this case:

     foreach($_FILES as $file) $file['file']['name'] $file['file']['tmp_name'] 

    And look what you have in the array print_r($_FILES)