Reputation: 9066
I have some image collection in my specied directory.And i want to get their name using readdir() function.But instead of showing their names,it prints out a series of 1.How this can be done correctly ??I also want to know the reason for this behaviour
$dir='c:/xampp/htdocs/practice/haha/';
echo getcwd().'</br>';
if(is_dir($dir)){
echo dirname($dir);
$file=opendir($dir);
while($data=readdir($file)!==false){
echo $data.'</br>';
}
}
Upvotes: 1
Views: 31
Reputation: 2731
You probably can implement instead with scandir
function list_directory($directory) {
$result = new stdClass();
$result->path = $directory;
$result->children = array();
$dir = scandir($directory);
foreach($dir as $file) {
if($file == '.' || $file == '..') continue;
$result->children[] =
!is_dir($directory.$file) ? $file :
list_directory($directory.$file.'/');
}
return $result;
}
$dir='c:/xampp/htdocs/practice/haha/';
$result = list_directory($dir);
echo '<code><pre>';
var_dump($result);
echo '</pre></code>';
You can add in the function a filter for filetypes, or limit depth of recursion, things like that.
Upvotes: 1
Reputation: 1677
$data=readdir($file)!==false
You're setting the boolean result to $data
. Surely you meant to do:
($data=readdir($file))!==false
Upvotes: 0
Reputation: 360712
Operator precedence. This line:
while($data=readdir($file)!==false){
is being parsed/executed as
while ($data = (readdir($file) !== false))
^------------------------^
Note the extra brackets. $data
is getting the boolean TRUE result of the !==
comparison. You need to rewerite as
while(($data = readdir($file)) !== false){
^----------------------^
That'll make $data
get the string returned from readdir
, and then that string will be compared with boolean false
.
Relevant docs: http://php.net/manual/en/language.operators.precedence.php
Upvotes: 4