PHP scan directory and array -


i have script scans folder , put in array file names contains. shuffle array , display file names.

like this:

$count=0; $ar=array(); $i=1; $g=scandir('./images/');  foreach($g $x) {     if(is_dir($x))$ar[$x]=scandir($x);     else      {          $count++;         $ar[]=$x;        } } shuffle($ar);  while($i <= $count) {     echo $ar[$i-1];     $i++; } ?> 

it works reason this:

  • fff.jpg
  • ccc.jpg
  • array
  • nnn.jpg
  • ttt.jpg
  • sss.jpg
  • bbb.jpg
  • array
  • eee.jpg

of course, order changes when refresh page because of shuffle did among 200 filenames these 2 "array" somewhere in list.

what be?

thank you

just explain part wherein gives array.

first off, scandir returns following:

returns array of files , directories directory.

from return values, returned (this example, reference):

array (     [0] => . // current directory     [1] => .. // parent directory     [2] => imgo.jpg     [3] => logo.png     [4] => picture1.png     [5] => picture2.png     [6] => picture3.png     [7] => picture4.png ) 

those dots right there folders. right in code logic, when hits/iterate spot:

if(is_dir($x))$ar[$x]=scandir($x); // if directory // invoke set of scandir directory, append array 

thats why resultant array has mixed strings, , extra/unneeded scandir array return values ..

a dirty quick fix used in order avoid those. skip dots:

foreach($g $x) {     // skip dots     if(in_array($x, array('..', '.'))) continue;     if(is_dir($x))$ar[$x]=scandir($x);     else     {         $count++;         $ar[]=$x;     } } 

another alternative use directoryiterator:

$path = './images/'; $files = new directoryiterator($path); $ar = array(); foreach($files $file) {     if(!$file->isdot()) {         // if not directory         $ar[] = $file->getfilename();     } }  echo '<pre>', print_r($ar, 1); 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -