Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Kusanagi's avatar

sort File::files(public_path('img'))

Hello I have a folder containing images and I want to show them on my page. So I did this

@foreach (File::files(public_path('img')) as $file)

            <img src="/img/{{ $file->getFilename() }}"/>

        @endforeach

The problem is as follows:

the name of the images are img_1, img_2,....,img_90

On my website the images get shown in this order : img_1, img_10, img_11, ..., img_2, img_20 etc. I want them to be in this order : img_1, img_2, img_3 etc.

How can I do this ?

0 likes
5 replies
Charizard's avatar
Level 5

@yasin masmoudi You will need a custom sort function, this is a rough implementation but i'm pretty sure it could be made cleaner and more optimized using collections:

private static function my_compare($a, $b){
	if(strlen($a->getFileName()) > strlen($b->getFileName()))
		return -1;

	if(strlen($b->getFileName()) > strlen($a->getFileName()))
		return 1;

	return (a->getFileName() < b->getFileName()) ? -1 : 1;
}

and then on your controller you would sort the array before passing it to your view like so:

$files = File::files(public_path('img'))

usort($files, array("controller_class", "my_compare"));

Anyway that's a very rough idea. hope it helps.

1 like
Kusanagi's avatar

Thank you for your help, I tried what you told me but I got this error :

usort() expects parameter 2 to be a valid callback, class 'controller_class' not found

I tried to implement it like this, since both the function my_compare and the usort are in the same controller :

usort($files, "my_compare");

but then I got this error : usort() expects parameter 2 to be a valid callback, function 'my_compare' not found or invalid function name

I am not sure where the problem might be

itsfg's avatar

If the functions are in the same controller, try as second parameter : array($this, 'my_compare')

1 like
Kusanagi's avatar

thx a lot. It worked :D. Could you please explain to me why array($this, 'my_compare') worked and what I did, did not ?

Charizard's avatar

'controller_class' was just an example because i didn't know the name of your controller, you could have either replaced it with the actual name of your controller or with $this since you are calling it from within your controller. Hope that makes sense.

1 like

Please or to participate in this conversation.