ConFoo Montreal 2026: Call for Papers

Voting

: eight plus one?
(Example: nine)

The Note You're Voting On

hxss at ya dot ru
7 years ago
The TRUE recursive map function for working with dirs & files.
You can create, read(find), update(or move) or delete files/dirs/tree by your callable function.
You can use flags for select what content you need.

<?php
var_dump
(dirmap($dst, function($v) {
pre($v);
return
true;
},
1|2|4|8));

/**
* Applies the callback to the entries of the given dir path
* In accordance with the received flags
* @param string $path path of the working directory
* @param Callable $action Callable function that would be
* executed for every entry in path
* @param integer $flags can be the following flag:
* 1: apply Callable function for files
* 2: apply Callable function for directories
* 4: apply Callable function for $path
* 8: work recursively
* @return bool bitwise AND of all (bool)$action calls results
*/
function dirmap(string $path, Callable $action, int $flags = 15) {
$flF = boolval($flags & 1);
$flD = boolval($flags & 2);
$flP = boolval($flags & 4);
$flR = boolval($flags & 8);
$result = 1;

if (
is_dir($path)) {

$dir = opendir($path);
while (
$entry = readdir($dir))
if (!
in_array($entry, ['.', '..'])) {
$fullEntry = "{$path}/{$entry}";

if (
$flR)
$result &= dirmap($fullEntry, $action, $flags & 11);

if (
$flF && is_file($fullEntry) || $flD && is_dir($fullEntry))
$result &= (bool)call_user_func($action, $fullEntry);
}

if (
$flP)
$result &= (bool)call_user_func($action, $fullEntry);

return (bool)
$result;
} else
return
is_file($path);
}
?>

<< Back to user notes page

To Top