I have this files path/0.php path/3.php path/2.php path/7.php
I want to display the files with foreach and I use this code:
$files = glob("system/$var/$var/$var/*/*.php");
foreach($files as $file) {
//code here per $file.
//for example:
$basename = basename($file);
echo str_replace(".php",null,$basename) . "<br>";
include $file; //heres i need the path of the files.
}
But I want to sort this files by the largest number that is before the .php extension, like this:
Array
(
[0] => path/7.php
[1] => path/3.php
[2] => path/2.php
[3] => path/0.php
)
so?
update, rsort is not good for me, because the is a path/to/file, before the numbers, i want to use the path of the files.
You can sort the array being returned using usort:
$files = glob("system/$var/$var/$var/*/*.php"
usort($files, function ($b, $a) {
return strcmp( substr($a, strrpos($a, '/') + 1),
substr($b, strrpos($b, '/') + 1) );
});
Note that this will use string comparison, so 10.php will end up between 1.php and 2.php. If that's not what you want you have to use numeric comparison. i.e. using PHP 7's "spaceship" operator:
$files = glob("system/$var/$var/$var/*/*.php"
usort($files, function ($b, $a) {
return ((int)substr($a, strrpos($a, '/') + 1))
<=> ((int)substr($b, strrpos($b, '/') + 1));
});
Edit: I swapped $a and $b in the callback signatures to reverse the sorting order
$files = glob("system/$var/$var/$var/*/*.php");
//Put each file name into an array called $filenames
foreach($files as $i => $file) $filenames[$i] = basename($file);
//Sort $filenames
rsort($filenames);
//Check output
print_r($filenames);
This will output:
Array
(
[0] => 7.php
[1] => 3.php
[2] => 2.php
[3] => 0.php
)
To preserve the full paths, you can use the paths as the keys and the basename as the values:
#For testing:
#$files = array("path/3.php", "path/1.php", "path/5.php", "path/7.php", "path/0.php");
//Put each path AND basename into an array called $filenames
foreach($files as $file) $filenames[basename($file)] = $file;
//Sort $filenames by basename with arsort()
arsort($filenames);
//Check output (listing the paths)
foreach($filenames as $k => $v) echo $v.PHP_EOL;
//Just the values
$filenames_with_paths = array_values($filenames);
print_r($filenames_with_paths);
This will output:
path/7.php
path/5.php
path/3.php
path/1.php
path/0.php
Array
(
[0] => path/7.php
[1] => path/5.php
[2] => path/3.php
[3] => path/1.php
[4] => path/0.php
)
User your code like :
foreach(array_reverse($files) as $filename){}
$files = glob("system/$var/$var/$var/*/*.php");
rsort($files);
foreach($files as $key){
echo $key;
}