'Undefined offset PHP' in a "for" loop

Asked

Viewed 198 times

-2

I’m trying to organize some folders in order in an application I’m doing for FTP. Follow the code I’m using:

    if ($file->isDir()) {
                    echo '<table>';
                    $archive = [$file];
                    for($i = 0; $i <= $archive; $i++){
                        echo '<tr></tr>';
                        echo '<td><a href="index.php?path='.$dir. DIRECTORY_SEPARATOR .$archive[$i].'"><img src="icones/archive.ico" width="30px" height="30px"/></a></td>' . $file->getBaseName();
                    }       
                    echo '</table>';
                } else {
                    switch($file->getExtension()) {
  Restante do código...

Error that appears on screen:

Undefined offset: 1

This error the top falls in an infinite loop.

  • 2

    Strange that $archive = [$file];, what is the intention? What shows a var_dump($file);?

  • $file is an object? Why is $Archive = [$file]?

  • $file are the FTP folders I want to organize.

  • $i <= count($archive)?

2 answers

2

Your current code presents a number of problems regarding the use of variables, matrices, objects and HTML. The suggestion to resolve each of the issues is extensive and lacks the rest of the code you use until you reach the excerpt that is in your question.

Some of the visible problems in your question:

  1. $file is an object, but you’re going through the same as the matrix key $archive;

  2. Your cycle for() would only work with the implementation you have, if the matrix $archive had numerical keys;

  3. You’re output from <tr></tr> and only then do you output <td></td>. As TD has to be inside the TR.

  4. He’s working the matrix $archive as if it had numeric keys which is what the variable $i contains. (see paragraph 1);

  5. You are concatenating $file->getBaseName() after you close the TD. It would have to be concatenated before the TD be closed;

  6. If there are no results, you will have a table with no contents;


List Files and Directories

From what I understand, you intend to list files and directories of a certain path to present to the user. Below follows a working example that illustrates this:

<?php

$outputHtml = '';

$pathToList = dirname(__FILE__);            // caminho a listar
$dir = new DirectoryIterator($pathToList);  // Iterar o caminho

// por cada entrada encontrada
foreach ($dir as $fileinfo) {

  // se não for "." ou ".."
  if (!$fileinfo->isDot()) {

    /* Verificar se é directoria ou ficheiro
     * para definir o icon a utilizar
     */
    if ($fileinfo->isDir()) {
      $icon = 'https://cdn2.iconfinder.com/data/icons/snipicons/5000/folder-close-32.png';
    }
    else {
      $icon = 'https://cdn2.iconfinder.com/data/icons/snipicons/500/file-32.png';
    }

    /* actualizar a variável de output com o HTML
     * referente a este ficheiro/directoria
     */    
    $outputHtml.= '
    <div>
      <a href="index.php?path='.$fileinfo->getPathname().'">
        <img src="'.$icon.'" width="32px" height="32px"/> '.$fileinfo->getFilename().'
      </a>
    </div>';
  }
}

/* Apresentar a listagem ou se não temos
 * resultados apresentar uma mensagem.
 */
if (!empty($outputHtml)) {
  echo $outputHtml;
}
else {
  echo '<p>Não foram encontrados ficheiros ou directorias para o caminho indicado!</p>';
}

?>

The code above will give you a listing similar to the screenshot below:

Exemplo da Listagem

Briefly, what is being done is:

  1. Set the path to list in the variable $pathToList:

    $pathToList = "/caminho/para/destino/*";
    
  2. Making use of the method DirectoryIterator (English) we built an iteration of the directory:

    $dir = new DirectoryIterator($pathToList);
    
  3. For each input located, we perform the intended actions. In the example above we are listing the localized content by assigning an icon for when it is a file and another icon for when it is a directory.

    foreach ($dir as $fileinfo) {
      ...
    }
    
  4. We present the result to the user if we have found something, if not, we present a message.

1

You have a array in his for - This won’t work. Try this:

for($i = 0; $i <= $file; $i++) {
    // o seu código aqui
}

If not, let’s think: you have a condition $file->isDir(), which means that $file does not have more than one value - it is to be an object - and you are the vectoring, what doesn’t make sense.

In more technical words, you are converting a singular object to a vector, and to the for That’s useless and it won’t work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.