0

Possible Duplicate:
Loop code for each file in a directory

I assumed that I can reach this with following code but i think i make someting wrong with this code include($file[$])

<?php
$dir= opendir(".") or die ('Cannot open directory');
$div="<div class=\"left1\">\n";
echo "<div class=\"wrapper\">\n";
for( $i=0; $i<6; $i++){
    while(($file = readdir($dir)) != false){
    if(preg_match("/php$/", $file)){
    echo $div;
    include($file[$i]); // HERE ITS NOT WORKING AS I WANT
    echo "</div>\n";
    }
    }
}
echo "</div>\n";

?>
Community
  • 1
  • 1

2 Answers2

3

readdir returns the actual filename as a string, so you're trying to access that filename as an array, which'll extract just one CHARACTER of that filename.

Try:

include($file);

instead. Beyond that, there's no need for opendir/readdir, you could just use glob():

$phpfiles = glob('*.php');
foreach($phpfiles as $file) {
    include($file);
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
2

$file is a plain string at this point, not an array. So instead of include($file[$i]), you merely need to include($file).

while(($file = readdir($dir)) !== false){
  if(preg_match("/php$/", $file)){
      echo $div;
      include($file);
      echo "</div>\n";
   }
}

The entire outer for loop appears to be unnecessary.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • but i need 6 different php files to be included in 6 div tags , in horizantal direction along to page, and the next 7. php file must be included again below in same way to different 6 er div groups, its the reason i used for loop, i think i should use foreach maybe thx – Hilmi Sleyman Tunahan Demirkay Jun 21 '12 at 17:32
  • @HilmiSleymanTunahanDemirkay Does it do what you want it to with the `for` loop as you have it? If I understand and you want to include the same group of files 6 times, then you will need to close the directory handle via `closedir()` and reopen it with `opendir()` on each loop of your `for` loop. – Michael Berkowski Jun 21 '12 at 17:36
  • No it does not do what i want with for, it s just to give it a try, i think your recommadations brings me more near to my goal. – Hilmi Sleyman Tunahan Demirkay Jun 21 '12 at 17:43