I am trying to get a random file from all subfolders in a folder.
First I get an iterator of all files, using this code:
$path = "/path/to/folder";
$folder = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($folder);
$files = new RegexIterator($iterator,
'/^.+\.(jpg|jpeg|png|gif)$/i',
RecursiveRegexIterator::GET_MATCH);
This appears to work (and finishes in a split second). Now I want to get a random item from the resulting iterator. I use this code (this is line 14):
$image = array_keys(iterator_to_array($files))[mt_rand(0,
count(iterator_to_array($files)) - 1)];
The folder contains 334327 † objects, and, after executing for a couple of seconds, iterator_to_array()
dies with the following error:
Fatal error: Allowed memory size of 134217728 bytes exhausted
(tried to allocate 1232 bytes) in /script.php on line 14
How do I need to change my code to avoid PHP running out of memory? Or is there a better way to grab a random item from such a huge array? (Or maybe it is even possible to grab a random file from all subfolders, directly?)
I do not want to override the memory limit!
† The number of files changes constantly.