How can the glob function in PHP be extended to output an array with key-value pairs?
The glob function in PHP can be extended to output an array with key-value pairs by iterating over the array of file paths returned by glob and assigning each path as a key in a new array with a corresponding value. This can be achieved by using a foreach loop to iterate over the glob result and using the basename function to extract the filename as the value for each key.
$files = glob("path/to/files/*");
$fileArray = [];
foreach ($files as $file) {
$fileArray[basename($file)] = $file;
}
print_r($fileArray);
Keywords
Related Questions
- How can the use of sprintf in the code snippet be optimized or improved for better performance?
- What are best practices for formatting and organizing PHP code to avoid errors?
- How can PHP developers ensure that their regular expressions only target specific parts of a string, such as replacing spaces within href attributes?