doudi2520 2018-09-26 23:28
浏览 81
已采纳

php max函数从数组返回最小值

this is my first post. sorry if i did something wrong...

anyways i have a file that gets updates by php and this is EXACTLY it:

31

127

131

124

144

142

133

133

9

0

22

18

i made this script in php:

$logContents = file_get_contents("logs/mainlog.txt");
$logitemArray = explode("
", $logContents);

echo max($logitemArray);

but it echos 9. why? it said in the php documentation that max() should return the biggest value in the array

thanks in advance

  • 写回答

2条回答 默认 最新

  • doumianfeng5065 2018-09-26 23:37
    关注

    explode() returns an array of strings, so they're being compared lexicographically. You need to convert them to numbers so that max() will compare them numerically.

    $logitemArray = array_map('intval', explode("
    ", $logContents));
    echo max($logitemArray);
    

    BTW, you can use the file() function to read a file directly into an array of lines, instead of using file_get_contents() followed by explode().

    $logitemArray = array_map('intval', file("logs/mainlog.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办