PHP 8.5.0 Alpha 1 available for testing

Voting

: seven plus zero?
(Example: nine)

The Note You're Voting On

kdouglas at satarah dot com
17 years ago
Breadth-first-search (BFS) for a file or directory (vs. Depth-first-search)
http://en.wikipedia.org/wiki/Breadth-first_search

<?php

// Breadth-First Recursive Directory Search, for a File or Directory
// with optional black-list paths and optional callback function.
//
// $root -- is the relative path to the start-of-search directory
// $file -- is the qualified file name: 'name.ext' EX: 'data.xml'
// (or) $file -- is the target directory name EX: 'xml_files'
// $callback -- is an optional function name and will be passed all
// matching paths EX: 'my_func', instead of exiting on first match
// $omit -- is an optional array of exclude paths -- relative to root
// To use $omit but not $callback, pass NULL as the $callback argument
//
// TESTING VALUES FOLLOW ...

function my_func ( $path ) {
print
"<strong>$path</strong><br>\n";
}

$root = '../public_html';
$file = 'data.xml';
$callback = 'my_func';
$omit = array( 'include/img', 'include/css', 'scripts' );

//print breadth_first_file_search ( $root, $file );
//print breadth_first_file_search ( $root, $file, $callback );
//print breadth_first_file_search ( $root, $file, NULL, $omit );
print breadth_first_file_search ( $root, $file, $callback, $omit );

function
breadth_first_file_search ( $root, $file, $callback = NULL, $omit = array() ) {
$queue = array( rtrim( $root, '/' ).'/' ); // normalize all paths
foreach ( $omit as &$path ) { // &$path Req. PHP ver 5.x and later
$path = $root.trim( $path, '/' ).'/';
}
while (
$base = array_shift( $queue ) ) {
$file_path = $base.$file;
if (
file_exists( $file_path ) ) { // file found
if ( is_callable( $callback ) ) {
$callback( $file_path ); // callback => CONTINUE
} else {
return
$file_path; // return file-path => EXIT
}
}
if ( (
$handle = opendir( $base ) ) ) {
while ( (
$child = readdir( $handle ) ) !== FALSE ) {
if (
is_dir( $base.$child ) && $child != '.' && $child != '..' ) {
$combined_path = $base.$child.'/';
if ( !
in_array( $combined_path, $omit ) ) {
array_push( $queue, $combined_path);
}
}
}
closedir( $handle );
}
// else unable to open directory => NEXT CHILD
}
return
FALSE; // end of tree, file not found
}

?>

<< Back to user notes page

To Top