dongpu1908 2018-03-31 17:23
浏览 27
已采纳

计算foreach循环外的所有结果值

I would like to count all characters in text files in certain path, so i've wrote the following code

<?PHP

$files = glob('my/files/path/*.txt', GLOB_BRACE); 

foreach($files as $file) { 

$str = file_get_contents($file) or dir("can not read file");

$numCharSpace = strlen($str);

echo "Counted " .$numCharSpace. " character(s).<br>";

} 

?>

Let say, we have 4 files inside this path so it will print out the following

Counted 201 character(s).
Counted 99 character(s).
Counted 88 character(s).
Counted 112 character(s).

How can i get the total of all which should be 500 character(s) so how to print out the count of all results which are inside foreach(); loop.

  • 写回答

4条回答 默认 最新

  • doupao1530 2018-03-31 17:27
    关注

    With strlen you get the number of the bytes of the file. So, you can as well get that directly, without the need to read the file contents.

    $numberOfChars = array_sum(
        array_map('filesize', glob('my/files/path/*.txt', GLOB_BRACE))
    );
    

    What this does is get the file size for each one of the files returned by glob, and sum them using array_sum.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记