PHP: ¿Qué hay de malo en este código y por qué no se incrementa la variable?

$blogDir = 'blog/';
$blogdirHandle = opendir( $blogDir );
$checkingFile;
$number = 0;
$codeNumber = '-'.$number.'-';
if( $blogdirHandle = opendir( 'blog/' ) )
{
    while( ( $checkingFile = readdir( $blogdirHandle ) ) !== false ) 
    {
        if( $checkingFile != '.' && $checkingFile != '..' && !is_dir( $checkingFile ) && strpos( $checkingFile, $codeNumber ) !== false )
        {
            $number++;
        }
    }
    closedir( $blogdirHandle );
}

Lo que intento hacer es:

Go through the $blogDir directory, and search for a file that has the same $codeNumber ( -$number- ), and if a file is found, then increase $number by one and search until all files are searched through. For some reason it's not working. It won't increase the value of $number, even though there are files with the same $codeNumber in the directory.. Any help?

preguntado el 09 de marzo de 12 a las 21:03

1 Respuestas

Once you increment $number, you need to re-assign $codeNumber dentro de tu bucle:

if( $blogdirHandle = opendir( 'blog/' ) )
{
    while( ( $checkingFile = readdir( $blogdirHandle ) ) !== false ) 
    {
        if( $checkingFile != '.' && $checkingFile != '..' && !is_dir( $checkingFile ) && strpos( $checkingFile, $codeNumber ) !== false )
        {
            $number++;
            $codeNumber = '-'.$number.'-';
        }
    }
    closedir( $blogdirHandle );
}

respondido 09 mar '12, 22:03

Yep. Thanks so much. I knew the answer was something stupidly simple like that, but I just couldn't put my finger on it. - user1219742

By the way, there's also an issue with the call to is_dir(). You need to add the blog/ directory to it like this: !is_dir( $blogDir.$checkingFile ) - it's working anyway though, because if the file doesn't exist it returns false. - pglhall

might make sense to put $codeNumber = '-'.$number.'-'; at the beginning of the while, instead of outside, or in the if - Ascherer

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.