如何使用PHP在目录中找到前5个文件? [英] How do I find the first 5 files in a directory with PHP?

查看:105
本文介绍了如何使用PHP在目录中找到前5个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何列出用PHP按字母顺序排序的目录中的前5个文件或目录?

解决方案

使用scandir():

array_slice(array_filter(scandir('/path/to/dir/'), 'is_file'), 0, 5);

array_filter()is_file()函数回调一起确保我们只处理文件而不必编写循环,我们甚至不必关心...,因为它们是目录./p>


或使用glob() -它将与.htaccess 之类的文件名不匹配:

array_slice(glob('/path/to/dir/*.*'), 0, 5);


或使用glob() + array_filter() -将匹配文件名,例如.htaccess :

array_slice(array_filter(glob('/path/to/dir/*'), 'is_file'), 0, 5);

How would I list the first 5 files or directories in directory sorted alphabetically with PHP?

解决方案

Using scandir():

array_slice(array_filter(scandir('/path/to/dir/'), 'is_file'), 0, 5);

The array_filter() together with the is_file() function callback makes sure we just process files without having to write a loop, we don't even have to care about . and .. as they are directories.


Or using glob() - it won't match filenames like .htaccess:

array_slice(glob('/path/to/dir/*.*'), 0, 5);


Or using glob() + array_filter() - this one will match filenames like .htaccess:

array_slice(array_filter(glob('/path/to/dir/*'), 'is_file'), 0, 5);

这篇关于如何使用PHP在目录中找到前5个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆