Welcome to WebmasterWorld Guest from 54.226.147.190

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Stop List After xx Number of Entries

     

cookiemonster

2:37 am on Aug 19, 2010 (gmt 0)

5+ Year Member




<?php
function listFolders(){
$path = glob("*",GLOB_ONLYDIR); //the double \\ is not a typo you
//have to escape it
//if the path cannot be found
if(!($path)){
echo("The specified path could not be found.");
return;
}//if

//the path is valid
else{
foreach($path as $i){

echo $i;
echo "<br>";

}//foreach
}//else
}//populateDropdown
?>
<?php echo listFolders() ?>


Hi everyone,

The code above lists every folder in a specified directory. I'd like to know if there's any way to limit the number of displayed folders to, for example, the first 10.

Thanks!

dreamcatcher

7:06 am on Aug 19, 2010 (gmt 0)

WebmasterWorld Senior Member dreamcatcher is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Maybe a for loop instead?

$count = count($path);

for ($i=0; $i<($count>10 ? 10 : $count); $i++) {
echo $path[$i];
}

dc

morehawes

10:34 am on Aug 19, 2010 (gmt 0)

5+ Year Member



Maybe not the most elegant approach but looking at the readdir examples in the PHP docs [uk3.php.net...] you could edit the while loop so it breaks when a certain condition is met :


$count = 0;
while (false !== ($file = readdir($handle))) {
echo "$file\n";
$count++;
if($count == 10) {
break;
}
}


A little crude but you get the idea. You would also need to check that $file is a directory.

rocknbil

5:16 pm on Aug 19, 2010 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Right, I'd be using that . . .but given what you have here,


<?php
function listFolders($path,$recurse_limit=null){
$counter=0;
$dirlist=$dir_errors=null;
//if the path cannot be found
if(! is_dir($path)){
return Array (null,"The specified path could not be found.");
}//if
//the path is valid
else{
foreach($path as $i){
$counter++;
$dirlist .= "<li>$i</li>\n"; // Retentive about semantics is Padawan
if ($recurse_limit and ($counter >= $recurse_limit)) {
break;
}
}//foreach
}//else
return Array($dirlist,$dir_errors);
}//listFolders
?>
//
<?php
// assuming GLOB_ONLYDIR is a constant
$dir_limit = 10;
list($dirs,$errors) = listFolders(GLOB_ONLYDIR,$dir_limit);
echo ($errors)?"Error: $errors":"<ul>$dir</ul>";
?>


You really don't need $dir_errors as you only have one error check, but it may be that you might add more later. So instead of

return Array (null,"The specified path could not be found.");

you could do

$dir_errors .= "<li>The specified path could not be found.</li>";

and

$dir_errors .= "<li>Some other error</li>";

then they both return at the end of the function.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month