Fill up an array IF statement - php

<?php
if ($handle = opendir('gallery3/var/thumbs/Captain-America/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";?><br/><?
echo rtrim($file, '.jpg');?><br/><?
$names[]=$file;
}
}
closedir($handle);
}
?>
I want to createa an array of the file names that are outputting and also the rtrim elements.

glob (coupled with array_map) may do a better job, but you can create an array, and add matches to it very simply:
$files = array(); // declare
...
$files[] = rtrim($file,'.jpg'); // adding entry
...
print_r($files); // debug output to see it
The glob example:
// with or without the array_map to basename()
$files = array_map('basename',glob('gallery3/var/thumbs/Captain-America/*'));
var_dump($files); // normal files
$files_rtrim = array_map(create_function('$f','return rtrim($f,".jpg");'),$files);
var_dump($files_rtrim); // rtrim version of same files

Related

array_diff in php returning only one unmatched value even if it is not duplicate

While running below code array_diff is returning only one value. However it should return two values. My first array holds:
access.2018.08.09.log
access.2018.08.10.log
access.2018.08.12.log
My second array holds:
access.2018.08.09.log
array_diff() is returning only: access.2018.08.12.log
Can someone please guide why is it happening.
<?php
$files = scandir('C:\wamp64\www\MyLogs\logsfiles');
foreach($files as $file) {
if($file == '.' || $file == '..') continue;
$S1=array($file.PHP_EOL);
print_r($S1);
}
$S2 =explode("\n", file_get_contents('uplodedregistry.txt'));
$result = array_diff_assoc($S1, $S2);
print_r($result);
?>
You keep overwriting your $S1 variable - so at the end of the loop, it will only hold one element - the last value from your loop. Instead, instantiate the array before the loop, and append to it inside the loop.
<?php
$files = scandir('C:\wamp64\www\MyLogs\logsfiles');
$S1 = array(); // Init the array here
foreach($files as $file) {
if($file == '.' || $file == '..')
continue;
$S1[] = $file.PHP_EOL; // Append to $S1
}
$S2 = explode("\n", file_get_contents('uplodedregistry.txt'));
$result = array_diff($S1, $S2);
print_r($result);

How to read the files and directories inside the directory

Can any one please let me know how to read the directory and find what are the files and directories inside that directory.
I've tried with checking the directories by using the is_dir() function as follows
$main = "path to the directory";//Directory which is having some files and one directory
readDir($main);
function readDir($main) {
$dirHandle = opendir($main);
while ($file = readdir($dirHandle)) {
if ($file != "." && $file != "..") {
if (is_dir($file)) {
//nothing is coming here
}
}
}
}
But it is not checking the directories.
Thanks
The most easy way in PHP 5 is with RecursiveDirectoryIterator and RecursiveIteratorIterator:
$dir = '/path/to/dir';
$directoryIterator = new RecursiveDirectoryIterator($dir);
$iterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $path) {
if ($path->isDir()) {
// ...
}
}
You don't need to recurse by yourself as these fine iterators handle it by themselves.
For more information about these powerful iterators see the linked documentation articles.
You have to use full path to subdirectory:
if(is_dir($main.'/'.$file)) { ... }
Use scandir
Then parse the result and eliminate '.' and '..' and is_file()
$le_map_to_search = $main;
$data_to_use_maps[] = array();
$data_to_use_maps = read_dir($le_map_to_search, 'dir');
$aantal_mappen = count($data_to_use_maps);
$counter_mappen = 1;
while($counter_mappen < $aantal_mappen){
echo $data_to_use_maps[$counter_mappen];
$counter_mappen++;
}
$data_to_use_files[] = array();
$data_to_use_files = read_dir($le_map_to_search, 'files');
$aantal_bestanden = count($data_to_use_files);
$counter_files = 1;
while($counter_files < $aantal_files){
echo $data_to_use_files [$counter_files ];
$counter_files ++;
}
Look at the reference here:
http://php.net/manual/en/function.scandir.php
Try this
$handle = opendir($directory); //Open the directory
while (false !== ($file = readdir($handle))) {
$filepath = $directory.DS.$file; //Get all files/directories in the directory
}

PHP Array Blocklist

I've created this code to cycle through the folders in the current directory and echo out a link to the folder, it all works fine. How would I go about using the $blacklist array as an array to hold the directory names of directories I dont want to show?
$blacklist = array('dropdown');
$results = array();
$dir = opendir("./");
while($file = readdir($dir)) {
if($file != "." && $file != "..") {
$results[] = $file;
}
}
closedir($dir);
foreach($results as $file) {
if($blocked != true) {
$fileUrl = $file;
$fileExplodedName = explode("_", $file);
$fileName = "";
$fileNameCount = count($fileExplodedName);
echo "<a href='".$fileUrl."'>";
$i = 1;
foreach($fileExplodedName as $name) {
$fileName .= $name." ";
}
echo trim($fileName);
echo "</a><br/>";
}
}
array_diff is the best tool for this job -- it's the shortest to write, very clear to read, and I would expect also the fastest.
$filesToShow = array_diff($results, $blacklist);
foreach($filesToShow as $file) {
// display the file
}
Use in_array for this.
$blocked = in_array($file, $blacklist);
Note that this is rather expensive. The runtime complexity of in_array is O(n) so don't make a large blacklist. This is actually faster, but with more "clumsy" code:
$blacklist = array('dropdown' => true);
/* ... */
$blocked = isset($blacklist[$file]);
The runtime complexity of the block check is then reduced to O(1) since the array (hashmap) is constant time on key lookup.

Use PHP to list a directory and strip filenames down to integers

I'm got a small PHP project that requires using files with numbered names, like so:
folder/1.file
folder/2.file
folder/3.file
... etc.
What I need to do is get an array of these filenames (easy enough), and then strip them down to integers (eg: array( 1, 2, 3 )). I'm a novice at PHP so I'm not up to speed on it's string functionality.
Any advice you could give me would be appreciated. Thank you.
Something like this should work:
$di = new DirectoryIterator('path/to/files');
foreach($di as $finfo) {
if($finfo->isFile()) {
$fname = (int)$finfo->getBasename();
// do something
}
}
$fname inside the foreach loop will contain your integer.
$array = array();
foreach(glob('*.file') as $filename) {
$array[] = (int)$filename;
}
print_r($array);
<?php
$files = array();
foreach($scandir('folder') as $file) {
if ($file == '.' || $file == '..')
continue;
$files[] = (int)$file;
}
This casts the filenames to an integer, which effectively changes anything that starts with an integer followed by any characters to just the integer.
e.g.
"123text" => 123
"421" => 421
"other" => 0
$directory = 'your/directory';
if ($handle = opendir($directory))
{
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && is_file($directory . "/" . $file))
{
$file_id = (int)pathinfo($directory . "/" . $file,PATHINFO_FILENAME);
}
}
closedir($handle);
}
This should work fine.
You can use a regular expression:
foreach(scandir('/path/to/folder') as $file) {
$files[] = preg_replace("/[^0-9]+/", "", $file);
}

dynamic formation of array with incremental depth in PHP

I want to use a function to recursively scan a folder, and assign the contents of each scan to an array.
It's simple enough to recurse through each successive index in the array using either next() or foreach - but how to dynamically add a layer of depth to the array (without hard coding it into the function) is giving me problems. Here's some pseudo:
function myScanner($start){
static $files = array();
$files = scandir($start);
//do some filtering here to omit unwanted types
$next = next($files);
//recurse scan
//PROBLEM: how to increment position in array to store results
//$next_position = $files[][][].... ad infinitum
//myScanner($start.DIRECTORY_SEPARATOR.$next);
}
any ideas?
Try something like this:
// $array is a pointer to your array
// $start is a directory to start the scan
function myScanner($start, &$array){
// opening $start directory handle
$handle = opendir($start);
// now we try to read the directory contents
while (false !== ($file = readdir($handle))) {
// filtering . and .. "folders"
if ($file != "." && $file != "..") {
// a variable to test if this file is a directory
$dirtest = $start . DIRECTORY_SEPARATOR . $file;
// check it
if (is_dir($dirtest)) {
// if it is the directory then run the function again
// DIRECTORY_SEPARATOR here to not mix files and directories with the same name
myScanner($dirtest, $array[$file . DIRECTORY_SEPARATOR]);
} else {
// else we just add this file to an array
$array[$file] = '';
}
}
}
// closing directory handle
closedir($handle);
}
// test it
$mytree = array();
myScanner('/var/www', $mytree);
print "<pre>";
print_r($mytree);
print "</pre>";
Try to use this function (and edit it for your demands):
function getDirTree($dir,$p=true) {
$d = dir($dir);$x=array();
while (false !== ($r = $d->read())) {
if($r!="."&&$r!=".."&&(($p==false&&is_dir($dir.$r))||$p==true)) {
$x[$r] = (is_dir($dir.$r)?array():(is_file($dir.$r)?true:false));
}
}
foreach ($x as $key => $value) {
if (is_dir($dir.$key."/")) {
$x[$key] = getDirTree($dir.$key."/",$p);
}
}
ksort($x);
return $x;
}
It returns sorted array of directories.

Categories