Search code examples
phpwhile-loopdirectorynoticearray-filter

PHP Notice: Undefined offset: 1 while getting all directories


So as I was working for a dropdown menu to select with style people want to choose, I got this error:

Notice: Undefined offset: 1 in ...

The code:

<?php
$dirs=array_filter(glob('../styles/*'), 'is_dir');
$count=count($dirs);
$i = $count;
while($i>0){
    echo substr($dirs[$i], 10);
    $i=$i-1;
}
?>

I hope someone knows how to fix the error, Many thanks!


Solution

  • It's because the is_dir function removes items from the array which are not directories.
    But the keys will be untouched.

    You can use the GLOB_ONLYDIR flag instead of array_filter

    <?php
      $dirs   = glob( '../styles/*', GLOB_ONLYDIR );
      $count  = count( $dirs );
      $i      = ( $count - 1 ); // note: you must substract 1 from the total
    
      while( $i >= 0 ) {
        echo substr( $dirs[$i], 10 ); // i assumes that you want the first 10 chars, if yes use substr( $dirs[$i], 0, 10 )
        $i--;
      }
    
      /** With FOREACH LOOP **/
      $dirs = glob( '../styles/*', GLOB_ONLYDIR );
      $dirs = array_reverse( $dirs );
    
      foreach( $dirs as $dir ) {
        echo substr( $dir, 10 );
      }
    ?>